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 or operator issue

My code is;

$('#selector1') || $('#selector2').on('click',function(){ //Your code here });

but || not working, just getting $(‘#selector2’), not $(‘#selector1’).

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

>Solution :

this is correct the correct behavior.

The ".on" method allows you to add a listener on an object in the DOM. However, just like any method, it needs to be called on the object itself, just like you do in the selector2.

Now that we know that, what you actually want to do is put a listener on both selectors, not one or the other.

A clean way to do so would be to put your function outside of the on method and simply call the function for all the selectors on which you want to run this function once clicked.
This would be less obtrusive and more recommended!

This would look something like this :

const myFunction = function(){
    // your code here
}

$('#selector1, #selector2').on('click',myFunction);

Edit: Thanks to RoryMcCrossan, I updated the answer as he reminded me that jQuery has a clean way to select many items in the div.

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