Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Jquery to javascript – click() working with z document.getElementById

There was a need to rewrite the code written with jquery into js. I have little js code on my site and I see no reason to include a library such as jquery.

This works (Jquery):

$('#prime').click(function() {
  myFuction();
});

function myFunction() {
  $('.prime').toggleClass('fa-message');
  $('.prime').toggleClass('fa-xmark');
}

This doesn’t:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

    document.getElementById("prime").click(function() {
          myFuction();
        });
        
        function myFunction() {
          document.getElementByClassName("prime").classList.toggle("fa-message");
          document.getElementByClassName("prime").classList.toggle("fa-xmark");
        }
}

Why?

I tried to rewrite the code jquery to js and something didn’t work out.

>Solution :

The way you add an onclick event to a DOM element in vanilla javascript is using the following syntax:

object.onclick = function() {myScript};

for for your case it would look like:

document.getElementById("prime").onclick = function() {  myFuction(); };

Here is some supporting documentation to help:

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading