Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Click not working

Very simple onclick not firing.

creating divs in a loop containing the classes:

class="person glyphicon glyphicon-user"

and i've tried selecting the class the only way i know

$('.person')click(function(){
console.log("something";
});

it just won't work, i can however print them all with the same selector, and i can fire onclick events on

$('body div').click

so its a div with class person, which leaves me clueless

thanks in advance.

edit: no browser errors, no action, nothing. the method copy pasted from my code:

$('.person').click(function() {
    console.log("something");
});
like image 837
Kasper Sølvstrøm Avatar asked Dec 25 '22 22:12

Kasper Sølvstrøm


2 Answers

You have multiple possible issues ( and assuming those are only typo's in your question):

  1. Ensure you have jQuery added to your html file and all other jQuery usage comes after that link.

  2. Ensure your JS is wrapped by a $(document).ready(function(){});

  3. "creating divs in a loop containing the classes:" This leads to believe you are creating them via a JS loop? If it is then you need to call your $('.person').click(function(){}); after the loop. Creating an event on an element type ( class in this case ) does not apply to future elements.

like image 84
kemicofa ghost Avatar answered Dec 28 '22 10:12

kemicofa ghost


try to use jquery on instead of click

$( ".person" ).on( "click", function() {
console.log("something");
});
like image 41
Vladu Ionut Avatar answered Dec 28 '22 11:12

Vladu Ionut