Image link with JavaScript does not work

1

Ok, I know there are thousands of ways to do this (better and easier) but I just like to make it work. I am passing the images through JS and would like to assign the link of the same, however, it does not work ... The console does not return any error, could anyone help?

window.onload = function(){
    rdSocial = $("#social");

    var fb = '<img src="img/fb.png" value="1" class="img" onclick="redireciona(this);">';
    var twt = '<img src="img/twitter.png" value="2" class="img" onclick="redireciona(this);">';
    var insta = '<img src="img/insta.png" value="3" class="img" onclick="redireciona(this);">';

    rdSocial.innerHTML += fb;
    rdSocial.innerHTML += twt;
    rdSocial.innerHTML += insta;
}

function redireciona(obj){
    if(obj.value == "1"){
        window.location="#";
    }
}
    
asked by anonymous 11.04.2015 / 23:09

1 answer

2

You are mixing some concepts:

  • jQuery and native JavaScript

Using $('#social') will give you a jQuery object and not a DOM element where you can use .innerHTML . Or changes to native using .getElementById(id) or change to jQuery and you use .html(conteudo)

  • value is not an image property

The <img> element is not value . So it is read as attribute and for the look you have to use img.getAttribute('value') .

Tip: Do this with native code:

window.onload = function(){
    rdSocial = document.getElementById("social");

    var fb = '<img src="img/fb.png" value="1" class="img" onclick="redireciona(this);">';
    var twt = '<img src="img/twitter.png" value="2" class="img" onclick="redireciona(this);">';
    var insta = '<img src="img/insta.png" value="3" class="img" onclick="redireciona(this);">';

    rdSocial.innerHTML += fb;
    rdSocial.innerHTML += twt;
    rdSocial.innerHTML += insta;
}

function redireciona(el){
    var value = el.getAttribute('value');
    if(value == "1"){
        window.location="#";
    }
}
    
11.04.2015 / 23:26