Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate jQuery click(), hide() and fadeIn() to native JS

So, I'm trying hard to speed up my page (by avoiding some requests) and wonder if anyone knows how to keep the following code working without having to load the whole JQuery library:

$("#div1").click(function () {
    $("#div2).hide();
    $("#div3").fadeIn();
})

Ofcourse this code needs a JQuery library to work, but it's heavier than my page itself.

Is there a way,somewhere, to just select the code needed from the library and insert it inline (in my html)?

Thank You,

like image 546
Larry Avatar asked Mar 10 '23 22:03

Larry


2 Answers

CSS3 @keyframes is a clean way to do what you want without jQuery. Have a look at this thread, which has a demo. It actually runs smoother than jQuery's fadeIn.

like image 123
BobRodes Avatar answered Mar 27 '23 03:03

BobRodes


Here's an example using CSS for the fade and plain Javascript for triggering the changes:

document.getElementById('div1').onmousedown = function() {
  addClass('div2', 'hide');
  addClass('div3', 'show');
}

function addClass(id, className) {
  var el = document.getElementById(id);
  if (el.classList)
    el.classList.add(className);
  else
    el.className += ' ' + className;
}
#div2.hide {
  display: none;
}

#div3 {
  opacity: 0;
  transition: 0.3s opacity ease;
}

#div3.show {
  opacity: 1;
}
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
like image 35
Fabian Schultz Avatar answered Mar 27 '23 02:03

Fabian Schultz