sparecycle
sparecycle

Reputation: 2058

Element click event not actually working

Ok, I don't seem to get it. All I'm attempting to do for now is log the text inside of a specific element - #target - on a webpage when it is clicked. Is there anything obvious that might cause the following not to work?

<script type="text/javascript">
    jQuery("#target").click(function(){
    var selectorText = jQuery("#target").text();
    console.log(selectorText);
});

</script>

Upvotes: 0

Views: 66

Answers (2)

Felix
Felix

Reputation: 38102

Maybe your element has been dynamically created, try to use event delegation here:

jQuery(document).on('click', '#target', (function(){
    var selectorText = $(this).text();
    console.log(selectorText);
});

Also, make sure that you only add #target once since id is unique. If you intend to create it multiple times, then you need to use class instead.

Btw, for delegated event, you should bind them to the closest parent that is not dynamic instead of document.

Upvotes: 3

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

jQuery("#target") Your #targetdoes not exist before the DOM is loaded therefore jQuery can't attach a listener to it. Whether you do attempt to click it or not does not matter.

If you really don't want to put it in $(), try this:

$(document).on("click", "#target", function(){
    //do your thing
});

Upvotes: 3

Related Questions