Skip to content
View in the app

A better way to browse. Learn more.

MSFN

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

[JS] Converting a small jQuery script to vanilla JavaScript

Featured Replies

H,
After google for hours for a JavaScript that would hide a div for X(12) Hours if clicked X(2) Times. I was only able to find a jQuery script that would do this. :crazy:
Could someone help me to convert this jQuery script below in to a vanilla JavaScript? :}

http://jsfiddle.net/mbdu6vtg/

$(document).ready(function() {
  // If the 'hide cookie is not set we show the message
  if (!readCookie('hide')) {
    $('#popupDiv').show();
  }
  // Add the event that closes the popup and sets the cookie that tells us to
  // not show it again until one day has passed.
  $('#close').click(function() {
    $('#popupDiv').hide();
    createCookie('hide', true, 1)
    return false;
  });
});
// ---
// And some generic cookie logic
// ---
function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}
function eraseCookie(name) {
  createCookie(name,"",-1);
}

 

Edited by Outbreaker

Check:

document.addEventListener('DOMContentLoaded', function() {

  // If the 'hide cookie is not set we show the message
  if (!readCookie('hide')) {
    document.getElementById('popupDiv').style.display = 'block';
  }

  // Add the event that closes the popup and sets the cookie that tells us to
  // not show it again until one day has passed.
  document.getElementById('close').addEventListener('click', function() {
    document.getElementById('popupDiv').style.display = 'none';
    createCookie('hide', true, 1)
    return false;
  });

});

// ---
// And some generic cookie logic
// ---
function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function eraseCookie(name) {
  createCookie(name,"",-1);
}

Where:

$(document).ready(function() {
-or-
$(function() {
-by-
document.addEventListener('DOMContentLoaded', function() {
-or-
window.addEventListener('load', function() {
-or-
window.onload = function() {

$('#popupDiv').show();
-by-
document.getElementById('popupDiv').style.display = 'block';
-or-
document.querySelector('#popupDiv').style.display = 'block';

$('#close').click(function() {
-by-
document.getElementById('close').addEventListener('click', function() {
-or-
document.getElementById('close').onclick = function() {
  • Author

HI,

Do you know how to tweak the script so it will only hide the div if it gets clicked 3 times in 24 hours?

I also changed the code so that it would work with CSS Style "class" instead of "ID". Is below the proper JavaScript code to do that?

FROM:
document.getElementById('popupDiv').
TO:
document.getElementsByClassName('popupDiv')[0].

Edited by Outbreaker

First clarify that JavaScript on the client side is completely manipulable by that client

Check:

<style>
  .msg { border: solid; background: yellow; padding: 1em; }
</style>

<div class="msg">Hello</div>
<div class="msg">vicious</div>
<div class="msg">world!</div>

<script>
  var msgs = document.getElementsByClassName('msg');
  var cookie = document.cookie;
  var clks = 0;
  var rx = new RegExp('(clicks=)(\\d)+');
   
  // Check if exists cookie and get clicks count
  if ( cookie.match(rx) ) {
    clks = cookie.match(rx)[2];
  } else {
    createCookie('clicks', 0, 1);
  }
  
  // If click counts >= 3 hide msgs elements
  if ( clks >= 3 ) {
    for ( let i = 0; i < msgs.length; i++ ) {
      msgs[i].style.display = 'none';
    }
  }
  
  // Set onclick event to msgs elements
  for ( let i = 0; i < msgs.length; i++ ) {
    msgs[i].onclick = function() {
      this.style.display = 'none';
      clks++;
      createCookie('clicks', clks, 1);
    }
  }
  
  function createCookie(name, value, days) {
    let cookie = name + '=' + value;
    if (days) {
      // max-age is more simple, set time-life in seconds
      cookie += ';max-age=' + days * 24 * 60 * 60;
    }
    document.cookie = cookie;
  } 
</script>

Using cookie name: clicks with value: count of clicks

Using Regular Expresion (RegExp) for matching and extract cookie value

Using getElementsByClassName array-like for hide and set click event using keyword: this

Using max-age for cookie, it is simpler than calculating expiration datetimes

On live: https://jsbin.com/zavogaqexu/edit?html,output

  • Author

Interesting to watch how the script is editing the cookie. :cool:

One little question i tried to add a short delay to the script to close the div. This should be an easy Task. Well, that's what I thought it would be. :dubbio:

for ( let i = 0; i < msgs.length; i++ ) {
  msgs[i].onclick = function() {
    setTimeout(function(){
      this.style.display = 'none';
      clks++;
      createCookie('clicks', clks, 1);
    }, 3000);
  }
}

 

Edited by Outbreaker

 

'this' from .onclick is lost in the setTimeout function, setTimeout has own 'this', use a variable:

  // Set onclick event to msgs elements
  for ( let i = 0; i < msgs.length; i++ ) {
    msgs[i].onclick = function() {
      let m = this;
      setTimeout(function(){
        m.style.display = 'none';
        clks++;
        createCookie('clicks', clks, 1);
      }, 3000);
    }
  }

 

Edited by EdSon
} missing

  • Author

I tried it out, but their is still a bug hiding somewhere that prevents it from running with the Timeout code. :dubbio:I also tried a few other methods from the internet but without luck. <_<

Edited by Outbreaker

Create an account or sign in to comment

Recently Browsing 0

  • No registered users viewing this page.

Account

Navigation

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.