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

So, I try to speed up my page (avoiding some queries) and wonder if anyone knows how to save the following code without loading the entire JQuery library:

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

Of course, this code needs a jQuery library to work, but it is heavier than my page itself.

Is there a way, somewhere, to simply select the code needed from the library and paste it into a line (in my html)?

Thank,

+4
source share
5 answers

CSS3 @keyframesis a clean way to do what you want without jQuery. Check out this thread for a demo. It really works smoother than jQuery fadeIn.

+2

CSS Javascript :

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>
Hide result
+2

jQuery, JS, - :

document.getElementById('div1').onclick(function() {

  document.getElementById('div2').style.visibility = 'hidden';
  document.getElementById('div3').style.visibility = 'visible';

});

DOM, !

+1

fadeIn, .

function fadeIn(el) {
    el.style.opacity = 0;
    var tick = function() {
        el.style.opacity = +el.style.opacity + 0.01;
        if (+el.style.opacity < 1) {
            (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16)
        }
    };
    tick();
}
document.getElementById("div1").onmousedown = function () {
    document.getElementById("div2").style.display = 'none';
    fadeIn(document.getElementById("div3"));
};
+1

, , - jQuery. , .

$ = function(selector) {
    return document.querySelector(selector);
}
HTMLElement.prototype.hide = function() {
    this.style.visibility = "hidden";
    this.style.opacity = 0;
}
HTMLElement.prototype.fadeIn = function() {
    this.style.display = "block";
    this.style.visibility = "visible";
    this.style.opacity = 1;
}

fadeIn() CSS . 400 , jQuery: transition: opacity .4s ease;

+1

Source: https://habr.com/ru/post/1657871/


All Articles