Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery onclick on div

Tags:

jquery

I have a simple question. The following code works for all the tags:

$('*').click(function(e) {  
    alert(1);
});

But, when I try this code for the div with id "content":

$('#content').click(function(e) {  
    alert(1);
});

What am I doing wrong ?

like image 939
Etienne Noël Avatar asked Aug 12 '11 00:08

Etienne Noël


People also ask

Is jQuery click deprecated?

click() that can be used to attach or trigger event handlers. For a complete list of shorthand methods, see the events category. Deprecated in jQuery 1.8, removed in 1.9: The name "hover" used as a shorthand for the string "mouseenter mouseleave" .

What is difference between click and Onclick in jQuery?

So onclick creates an attribute within the binded HTML tag, using a string which is linked to a function. Whereas . click binds the function itself to the property element.

What is $( this in jQuery?

$(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this . Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.


3 Answers

Make sure it's within a document ready tagAlternatively, try using .live

$(document).ready(function(){

    $('#content').live('click', function(e) {  
        alert(1);
    });
});

Example:

$(document).ready(function() {
    $('#content').click(function(e) {  
      alert(1);
    });
});
#content {
    padding: 20px;
    background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="content">Hello world</div>

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.

$('#content').on( "click", function() {
    alert(1);
});
like image 198
Steve Robbins Avatar answered Oct 16 '22 06:10

Steve Robbins


Nothing.

$('#content').click(function(e) {  
    alert(1);
});

Will bind to an existing HTML element with the ID set to content, and will show a message box on click.

  • Make sure that #content exists before using that code
  • That the ID is unique
  • Check your Javascript console for any errors or issues
like image 32
foxy Avatar answered Oct 16 '22 04:10

foxy


js

<script
  src="https://code.jquery.com/jquery-2.2.4.min.js"
  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>


<script type="text/javascript">

$(document).ready(function(){
    $("#div1").on('click', function(){
            console.log("click!!!");
        });
});

</script>

html

<div id="div1">div!</div>
like image 3
Ryosuke Hujisawa Avatar answered Oct 16 '22 05:10

Ryosuke Hujisawa