Omar Omar - 7 months ago 12
Javascript Question

Javascript is not "opening" url's

I am not sure what's wrong with this script. It "should" work.

HTML

<img src="https://placehold.it/350x150" alt="" onclick="goTo('img1');">


Javascript

function goTo(img) {
if( img === 'img1' ) { window.open('https://www.google.com/','_blank'); }
else if( img === 'img2' ) { window.open('https://www.yahoo.com/','_blank'); }
etc...
else{ alert("This image is not recognized: " + img ); }
}


JsFiddle: https://jsfiddle.net/omarjuvera/xuzc70gn/2/




Edit: On the website, I have the javascrip code inside a .ready(), like so:

$( document ).ready(function() {

function goTo(img) {
if( img === 'ivory' ) { window.open('https://www.indiegogo.com/project/preview/a0d4cff9','_blank'); }
else{ alert("This image is not recognized: " + img ); }
}

...more functions...
});

Answer

Just put the goTo function outside of .ready() event like following:

function goTo(img) {
    if( img === 'ivory' ) { window.open('https://www.indiegogo.com/project/preview/a0d4cff9','_blank'); }
    else{ alert("This image is not recognized: " + img ); }
}

$( document ).ready(function() {

    ...more functions...


});