willsantoso
willsantoso

Reputation: 137

click event fired more than once ( supposed to be once)

this is my first post, here I wanted to create a chrome extension, when it is pressed, it will show links which can be pressed, links retrieved using AJAX. It worked so far, the only problem is when it is clicked on any link, sometimes it appeared twice or even thrice. can anyone give an explanation and answer to this problem?

Thank you!

var links = [];
links.push("http://www.tenmanga.com/book/rss/id-16896.xml");
links.push("http://mangafox.me/rss/fairy_tail.xml");
links.push("http://feeds.feedburner.com/9gag?format=xml");

Function Start()

function start(){
    for (var i in links)
        getXML(links[i]);
    $(document).ready(function(){
    });


}

Function getXML

function getXML(url){
    var test = $.ajax({
        type: "GET",
        url: url,
        dataType: "xml",
        success: function(xml){
            parse(xml);
bind();
        }
    });
    return test;
}

function bind(){
    $("a").click(function(e){
        chrome.tabs.create({url:$(this).attr("href")});
    });
}
function parse(xml){
    //$("#content").append();
    var title = $(xml).find('title').first().text();
    var createClickHandler = function(arg){
        return function(){ 
            open_item(arg); 
        };
    }
    $("#content").append(title+"<br>");
    $(xml).find('item').each(function(){
        var temp = document.createElement("a");
        var title = this.childNodes[1].textContent;
        var link = this.childNodes[3].textContent;
        temp.innerHTML = title;
        temp.setAttribute("href",link);
        $("#content").append(temp);
        $("#content").append("<br>");
    });
    $("#content").append("<br>");
}

START HERE!

var start = start();

Upvotes: 1

Views: 664

Answers (3)

jossie
jossie

Reputation: 229

The only reason to invoke click event more than once when clicked on an elements is, more than one event handler is registered over that. Each time you call bind what u have done is binding to event to 'a' so i guess for the first link it event is fired once for the seconds twice and for the third thrice.May be instead of using just $('a') that attributes to all the 'a' element in the page you may dynamically make 'a' with separate ids. That must end the weird behavior.

Upvotes: 1

zb&#39;
zb&#39;

Reputation: 8059

instead of binding on each link, do the following once:

$(document).on('click','a'
    function(e){
        chrome.tabs.create({url:$(this).attr("href")});
        return false;
    }
);

if you have no other anchors on link

Upvotes: 0

Marek
Marek

Reputation: 1878

Invoke e.preventDefault(); where e is event in your click callback so that event won't bubble up and won't trigger anything else.

Also bind() should not be called on each success after ajax returned.

Upvotes: 0

Related Questions