Jump to content

[JS] Converting a small jQuery script to vanilla JavaScript


Recommended Posts

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
Link to comment
Share on other sites


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() {
Link to comment
Share on other sites

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
Link to comment
Share on other sites

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

Link to comment
Share on other sites

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
Link to comment
Share on other sites

 

'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
Link to comment
Share on other sites

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
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...