Search code examples
jqueryhtmleventsbindmarkup

How can I bind event for html markup variable using jquery?


Suppose I have a variable which store html markup:

var $content=$("<div id='test'></div>")

then I want give it a click event,and append it to body element

$content.click(function(){
    console.log('click!');
});

$content.appendTo($('body'))

however it doesn't work ,how can I make it possible?


Solution

  • The click handler gets set up just fine. The problem is that with a completely empty div, it has a height of 0 (unless you've done styling somewhere that you haven't shown), and so you can't find it to click on it. Zero-height example | source.

    The solution is to put content in the div, or to give it styling to give it height:

    Content example | source:

    var $content=$("<div id='test'>I'm the div!</div>");
    $content.click(function(){
        console.log('click!');
    });
    $content.appendTo($('body'));
    

    Styling example | source:

    JavaScript:

    var $content=$("<div id='test'></div>");
    $content.click(function(){
        console.log('click!');
    });
    $content.appendTo($('body'));
    

    CSS:

    #test {
        height: 20px;
        border: 1px solid black;
    }
    

    Side note:

    Suppose I have a variable which store html markup:

    var $content=$("<div id='test'></div>");

    Note that you're not storing HTML markup. By calling jQuery with HTML markup, you're telling jQuery to create the relevant DOM elements and wrap them in a jQuery instance.

    To store markup in a variable, you'd just store the string containing the markup:

    var content="<div id='test'></div>";
    

    Markup is text; elements are objects.


    Update: Re your comment below:

    I write this code in jquery plugin js file...does it have some matter?

    It matters if your code is running before there's a body element to append to; your last line will fail without a body element (for instance, if you code is running immediately on load, and it's loaded from the head element). If the body element exists as of when you run your code, it should be fine.