Reputation: 12297
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
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
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>":
Upvotes: 1
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