Omar Juvera
Omar Juvera

Reputation: 12297

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 javascript 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...
});

Upvotes: 0

Views: 55

Answers (3)

Sajib Biswas
Sajib Biswas

Reputation: 463

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...


});

Upvotes: 2

Rhumborl
Rhumborl

Reputation: 16609

By default, JsFiddle runs your code on page load. In other words, it wraps your goTo() function in anther function, like this:

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

This makes it inaccessible from, for example, an onclick attribute in HTML.

To fix this, you need to change the Load type setting to "No wrap - in <body>":

enter image description here

See updated fiddle

Upvotes: 1

tobspr
tobspr

Reputation: 8376

Your goto function is not declared in global scope, and thus cannot be found. Try:

window.goTo = function (img) {
    // your code
}

Upvotes: 2

Related Questions