Search code examples
javascriptfirefox-os

Open all links in browser without jquery- Firefox OS


I found this solution on stackoverflow. But how is this possible without jquery?

$('a[href^=http]').click(function(e){
    e.preventDefault();

    var activity = new MozActivity({
    name: "view",
    data: {
              type: "url",
               url: $(this).attr("href")
          }
    });
 });

Solution

  • Here is a direct port using querySelectorAll and addEventListener:

    var els = document.querySelectorAll('a[href^=http]');
    for(var i=0,len=els.length;i<len;i++){
       els[i].addEventListener("click",function(e){
             e.preventDefault();
             var activity = new MozActivity({
                 name: "view",
                 data: { type: "url", url: this.href}
            });
        },false);
    }
    

    This will not work if you're dynamically adding links, for that you need to add the listener when you add the link or use event delegation.