Skip to content Skip to sidebar Skip to footer

How To Prepend Html Into On Page Element From Html Onclick Event?

I am attempting set up the ability to dynamically generate 'tooltip' popups when a user clicks on a specific element (a little question mark icon). These tooltips would be absolute

Solution 1:

Since you are using jQuery, how about make it use of it's listeners and add html data attributes?

<aclass="tooltip"data-h4="Test Tooltip"data-p="blah blah blah blah blah blah blah blah blah"><divclass="dialog-anchor">ANCHOR</div></a>

One thing that is wrong as well: $(this).next('.dialog-anchor') - .dialog-anchor is a child of .tooltip. next() is used when it's siblings, not childs. Use find instead.

$(function () { //jquery document.ready
    $('a.tooltip').on('click', function (e) {
        var $this = $(this);
        e.preventDefault();

        //dialog-anchor is a child of tooltip. NEXT is used when it's siblings
        $this.find('.dialog-anchor').prepend('<div class="dialog-container"><div class="tooltip-dialog"><h4>' + $this.data('h4') + '</h4><p>' + $this.data('h4') + '</p></div><div class="bg"></div></div>');
    });
});

http://jsfiddle.net/dg1t4f8c/3/

Solution 2:

You need to pass this as an argument to the function. The HTML attribute should be:

onClick="createTooltip(this, 'Test Tooltip', 'blah blah blah blah blah blah blah blah blah')"

And the jQuery should use .find(), not .next(), because the .dialog-anchor element is inside the anchor, not after it.

function createTooltip(elem, h4, p) {
    $(elem).find('.dialog-anchor').prepend('<divclass="dialog-container"><divclass="tooltip-dialog"><h4>'+h4+'</h4><p>'+p+'</p></div><divclass="bg"></div></div>');
}

DEMO

You would use .next() if the HTML were like this:

<a>something</a><divclass="dialog-anchor"></div>

Post a Comment for "How To Prepend Html Into On Page Element From Html Onclick Event?"