saikiran
saikiran

Reputation: 2445

Document click not working on dynamic element

Content script:

var $ = window.$.noConflict(true); // Required for IE

function startFunc() {

    $('a').mouseover(function(e){

        var anchor=this;
        var href=$(anchor).attr('href');

        if(href!='#'){

            $('.klik-me').remove();

            const xPos=e.pageX-20;
            const yPos=e.pageY-20;

            let $klikMe=$('<span class="klik-me">Click Me!!</span>').css({
                'padding':'5px',
                'background':'#000',
                'color':'#FFF',
                'font-size':'12px',
                'position':'static',
                'top':yPos,
                'left':xPos,
                'text-align':'center',
                'z-index':999999
            });

            $(anchor).append($klikMe);
        }

    });


}

$('body').on('click','.klik-me',function(){

    const href_in=$(this).parent().attr('href');

    kango.console.log(href_in);

    kango.dispatchMessage('storeHref', {href:href_in});
});


kango.addMessageListener('hrefSuccess', function(event) {

    kango.console.log(event.data.link);

});

Background Script:

kango.addMessageListener('storeHref', function(event) {

event.target.dispatchMessage('hrefSuccess', {link:event.data.href});

});

I am adding a pop up for all anchor tags on the page (this is working fine),i added a click event in Jquery(I love this) and using kango.dispatchMessage for sending message to background script. Nothing seems to be working.

Any help would be appreciated.

PS: i use to work with crossrider(Awesome) framework previously.

Upvotes: 0

Views: 371

Answers (2)

Phil
Phil

Reputation: 164897

What I think is happening is the click event is bubbling up to your <a> element and triggering the default navigation action.

Stopping bubbling / default behaviour in delegated event handling is difficult. What I would do instead, is remove the <span> as a child of the <a>. For example

let $klikMe = $('<span class="klik-me">Click Me!!</span>')
  .css({ ... })
  .data('href', href) // set the href data into the <span>

$(document.body).append($klikMe) // append to body, not anchor

and in your click handler

$(document).on('click', '.klick-me', function() {
  const href_in = $(this).data('href')

  // then continue as in your original code

  return false // the click should have no default action
})

Upvotes: 0

Kyriediculous
Kyriediculous

Reputation: 119

Use the snippet below is what I'm reading everywhere, I can't get it working however.

Currently trying to do somewhat the same: jQuery click event after new page loads

Maybe it can be of some use.

Cheers.

$(parent).on('click', child , callback);

Upvotes: -2

Related Questions