'if else with linked image
This might be a very simple one but been struggling a bit with it.
if (getCookie("Account")=="True"){ ... } else { ... }
I would like to add in the brackets of the if and else a linked image banner. One image if they have a account and another if they do not.
True
<a href="#" target="_blank"><img src="/images/imageTrue.jpg" alt="" /></a>
Else
<a href="#" target="_blank"><img src="/images/imageElse.jpg" alt="" /></a>
Thank You for any help
Solution 1:[1]
Here is an example:
if (getCookie("Account")=="True"){
$('#img').attr('src', '/images/imageTrue.jpg');
} else {
$('#img').attr('src', '/images/imageFalse.jpg');
}
// your getCookie function
function getCookie(){
return Math.random()*2>1?"True":"False";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" target="_blank"><img id="img" src="/images/imageTrue.jpg" alt="" />click me</a>
Solution 2:[2]
What have you tried at least ? To change the source of the image, select the image with jQuery with something like that :
$(document).ready(function(){
$('#id') // to select an id
$('.class') // to select a class
$('a') // to select all <a> tags
});
Then change the source and alt of image with attr function
$(document).ready(function(){
if (getCookie("Account")=="True"){
$('a').attr('href','http://example.com/');
$('img').attr({'src':'img/my-img-1.jpg', 'alt':'My alt'});
} else {
$('a').attr('href','http://example.com/');
$('img').attr({'src':'img/my-img-2.jpg', 'alt':'My alt'});
}
});
Here to help you : http://api.jquery.com/attr/
Solution 3:[3]
you can set this by accessing the element first and then set the src attribute with link. Ex:
var el=$('#id');
if (getCookie("Account")=="True"){
el.attr('src','/images/imageTrue.jpg');
}
else {
el.attr('src','/images/imageFalse.jpg');
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Terry Wei |
Solution 2 | Bambou |
Solution 3 | xxx |