Javascript if/else statement using image src as condition - javascript

I have a voting script with an arrow system (upvotes and downvotes).If user clicks upvote, the arrow changes to the green arrow, meaning vote registered. If they click again, I want the arrow to revert back to the original image. However, using my code, it changes the image on the first like, but doesn't revert back on a second click.
if (like.src = 'vote_triangle.png') {
like.src = 'vote_triangle_like.png';
} else {
like.src = 'vote_triangle.png';
}

Use a more lenient if statement like:
if (like.src.indexOf('vote_triangle.png')!=-1) {
like.src = 'vote_triangle_like.png';
} else {
like.src = 'vote_triangle.png';
}

I know it's a very old thread, but I would like to add my findings here for future reference.
I found the following code wasn't working:
function swapImage() {
var element = document.getElementById("myImage");
if (element.src == "image1.png") {
element.src = "image2.png";
} else {
element.src = "image1.png"
}
}
Showing alerts containing the element.src taught me it contained the full path to the image in my local machine. Thus, the if statement had been always evaluated to false.
To fix that in a logical manner, what I did was get the attribute of the element, as the following code shows.
function swapImage() {
var element = document.getElementById("myImage");
if (element.getAttribute("src") == "image1.png") {
element.src = "image2.png";
} else {
element.src = "image1.png";
}
}
By using the function getAttribute("attributeName"), I was able to retrieve the path contained in the src relatively to the project directory.

I would suggest, instead of using img soruce as conditional statement, use a global variable, change its state once the upvote is clicked by say +1 and for downvotes -1.
//when 0, show upvote image, make it a global by declaring before any function
var UpVote = 0;
//when upvote clicked, when greater than 0, show down vote img
UpVote = UpVote +1 ;
//conditional logic for img source
if(UpVote > 0){
like.src = 'vote_triangle.png';
}
else{
like.src = 'vote_triangle_like.png';
}

Related

The == is not working in my IF statement Function

i have a simple function (up) here its an arrow and onclick is should check for image 1 in the div "gallerymain" and if its there it should show image 2. ELSE if image 3 is displayed and it suppose to show image 4 .
however for some unknown reason the == isn't working (i checked with alert ) , i also made sure that all is in the right case and path . the funny thing is that if i will use = instead of == it will work but it onclick it will show image 2 no matter what (even if image 3 is there ) i understand why (because i am assigning the path to the src . maybe somebody please take a fresh look on it and see what am i missing.
thank you!
function up () {
if
(document.getElementById("gallerymain").src ==
"../images/gallery/image1.jpg")
{
document.getElementById("gallerymain").src =
"../images/gallery/image2.jpg"
}
else if
(document.getElementById("gallerymain").src ==
"../images/gallery/image3.jpg")
{
document.getElementById("gallerymain").src =
"../images/gallery/image4.jpg"
}
}
img.src getter (as in img.src == '../img.jpg') returns absolute URL that is http://mysite.dev/img.jpg. img.src setter (as in img.src = '../img.jpg') amends relative URL to absolute.
getAttribute method returns exactly what was assigned. So try this.
if
(document.getElementById("gallerymain").getAttribute('src') ==
"../images/gallery/image1.jpg")
{
document.getElementById("gallerymain").src =
"../images/gallery/image2.jpg"
}

Unable to change image src with JavaScript

I know this has been asked; and I've read most of the asked questions to no avail. I still am having trouble. I want to click an image and have the image source change (thus having the image change).
This is my HTML:
<img id="picture1" onclick="showHide('builder1'); change('picture1');" width="25" height="25" src="pictures/down.png">
Ignore the "showHide('builder1');". It's working. I need help on the change('picture1').
And this is my Javascript:
function change(id)
{
var isDown = true;
var picture = document.getElementById(id);
if(isDown === true)
{
picture.src = "pictures/pullup.png";
isDown = false; //No longer a down arrow...
}
else
{
picture.src = "pictures/down.png";
isDown = true;
}
}
I am able to change the picture once (to 'pictures/pullup.png') but can't change it back.
I also added alerts at certain points in the if/else statement to see where it was at; and it never even reached the 'else' part of the statement.
Move var isDown = true; outside the function scope - define it before the function.
This way, every time you run the function, you set the variable to true first.
Based on Mike's comment: you could also use something like this:
picture.src = "pictures/"
+ (picture.src=="pictures/pullup.png" ?
"pulldown.png"
: "pullup.png");
Or with an IF if you dislike ternary.
You are defining isDown in the same statement, everytime, to be true. So it will never reach the else block of your conditional statement.

Loading an image but onload/onerror not working as expected

I have a div
<div id='cards'>
Which I want to fill with images based on some logic. But only when images are first loaded into memory. Otherwise, through onerror I wanna fill in some text..
function pasteCard(card, to){
if (typeof(card) == 'string')
card = [card];
var image = [];
for (var i = 0; i < card.length; i++) {
image[i] = new Image();
image[i].src = '/sprites/open/' + card[i] + '.png';
image[i].onload = function() {
pasteImage(to, image[i]);
}
image[i].onerror = function() {
pasteText(to, card[i]);
}
// alert(card[i]) #1
}
function pasteImage(to, image) {
to.append(image);
}
function pasteText(to, text) {
// alert(card[i]) #2
to.append(text);
}
}
pasteCard(['ABC123', 'DEF456', 'GHI789'], $('#cards'));
But this isn't working.
Problem/weirdness: If only #2 alert is active it returns nothing. But strangely if #1 alert is also active it does kinda work... (but still doesn't load my images, and mostly fails too when other code is involved)
Question: Why is it not working without #1 alert (at least in that jsfiddle)
suggestions?: what should I do?
Onload and onerror events are fired (executed) outside the scope of your function so your variables will be undefined. In the event method you have access to this which is the image object. You can set a data attribute to each image and access that in your error event.
Here is an example:
http://jsfiddle.net/7CfEu/4/
The callbacks are not in the same scope as your image array is - therefor you need to declare a variable then will "connect the scopes" and use it inside the callbacks
also the i variable probably changes until the callback is fired - so by using it inside the callback you will get undefined behavior
for (var i = 0; i < card.length; i++) {
var current_card = card[i];
var current_image = new Image();
current_image.onload = function() {
pasteImage(to, current_image);
}
current_image.onerror = function() {
pasteText(to, current_card);
}
current_image.src = '/sprites/open/' + current_card + '.png';
image[i] = current_image;
}
Fiddle: http://jsfiddle.net/7CfEu/6/
(Also - closing the div tag is never a bad idea)
Just in case anyone ends up here for same reason I did.
Was going crazy because onload and onerror were not firing in the page I was building. Tried copy pasting
var myimage = new Image();
myimage.onload = function() { alert("Success"); };
myimage.onerror = function() { alert("Fail"); };
myimage.src = "mog.gif" //Doesn't exist.
Which was working within codepen and random otherwise blank pages.
Turns out the problem I was having was that I was doing AJAX requests earlier in the page. This involved authorization which in turn involved a call to
setRequestHeader();
This was resulting in a net::ERR_FILE_NOT_FOUND error instead of the expected GET mog.gif 404 (Not Found)
This seemed to prevent proper triggering of events.
Revert with
xhr.setRequestHeader("Authorization", "");

javascript: multiple stop image toggle

I am trying to make an image button on my website toggle wallpaper change frequency options (off,5,10,15,30,30,90 minutes). I have created a custom image for each step (so the user can be aware of the current setting). When implemented the user should be able to repeatedly hit the button to toggle through all 7 options, ultimately looping back to the beginning.
I have some code to swap between two images (below), and have used it for other options on the site (wallpaper on/off), but I just can't figure out a way to get the code to work for my new needs.
if (imageId == 'image1') {
if (document.getElementById) {
var img = document.getElementById(imageId);
img.src = (img.src.indexOf("40_unlocked.jpg") != -1) ? "40_locked.jpg" : "40_unlocked.jpg";
}
}
I expect I will need to determine the current image, then use a switch to advance to the next option, something like the below, but I don't know how to determine the current image - hoping someone can offer a suggestion - thanks in advance!
function changeIt(img) {
var src;
switch (img.id) {
case "example":
src = "n.gif";
break;
case "example2":
src = "n2.gif";
break;
case "example3":
src = "n3.gif";
break;
}
img.src = (img.src.indexOf("jj.gif") < 0 ? "jj.gif" : src);
}
This should get you started
Name your images n0.gif through n6.gif.
toggle.onclick=function(){
//isolate the number of the current image
var num=this.src.split('.gif')[0].split('n')[1]-0;
//add 1 and take mod 7 to loop it back to 0 if it needed
num=++num%7;
//set the src to the new image
this.src='n'+num+'.gif';
}
Try creating an array of all of the src urls & then toggle it like this.
function changeIt(img)
{
var src=img.src;
images=['src1','src2','src3','src4','src5','src6','src7'];
index=images.indexOf(a);
if (index+1>6)
{
index=0;
}
else
{
index+=1;
}
img.setAttribute('src',images[index]);
}

Inner HTML if statement not recognizing a div tag

I tested the following code in IE, Chrome, and Firefox and it does not work in any of them. I have read several questions about similar problems but they have not offered solutions that fix my example.
I am trying to create a pause/play button that interfaces with JWplayer (I also want it to interface with flowplayer, once I get the button working) and the image will change depending on which image is currently there. I also have a stop button that stops the player completely and changes the image of the pause/play button to pause.
Here is my current code:
<script type="text/javascript">
function changeimg()
{
var obj = document.getElementById('image1');
var imgtag1 = '<img src=\'PLAY.png\'>';
var imgtag2 = '<img src=\'PAUSE.png\'>';
if(obj.innerHTML == imgtag2)
{obj.innerHTML = imgtag1;}
else
{obj.innerHTML = imgtag2;}
return;
}
function playimg()
{
document.getElementById('image1').innerHTML = '<img src=\'PLAY.png\'>';
return;
}
</script>
<div id="image1" href="#" onclick="changeimg(); jwplayer('mediaspace1').play(); jwplayer('mediaspace2').play(); jwplayer('mediaspace3').play(); jwplayer('mediaspace4').play();"><img src='PLAY.png'></div>
<div href="#" onclick="playimg(); jwplayer('mediaspace1').stop(); jwplayer('mediaspace2').stop(); jwplayer('mediaspace3').stop(); jwplayer('mediaspace4').stop();"><img src='STOP.png'></div>
The play/pause function works, and the first div WILL change into the pause img (so the javascript is going through) and it WILL change back into play if I click on the second div (stop function - triggers playimg() ) but it will not change back into the play image if I click on the pause button again.
For security reasons I can't link the website, but any help would be appreciated
It looks like all you really want to change is the SRC of the IMG tag, not necessarily the entire innerHTML. As machineghost mentions in his comment, there may be whitespace added or other changes to the full HTML that may make your comparison come out as false.
However, you could check if obj.src == "PLAY.png" and set the SRC attribute directly. Something like this:
function changeimg()
{
var obj = document.getElementById('image1');
var img1 = 'PLAY.png';
var img2 = 'PAUSE.png';
if(obj.src == img2)
{obj.src = img1;}
else
{obj.src = img2;}
return;
}
I think the innerhtml you are replacing in changeimg() is affecting the whole obj element, which is a div. So, if(obj.innerHTML == imgtag2) will return false since the div innerhtml is not imgtag2, but the next time you are going to call changeimg(), "obj" will be undefined because you replaced its innerhtml with an HTML code that doesn't have an id: {obj.innerHTML = imgtag2;}
Check the console to see if there's any javascript error, which it should, at if(obj.innerHTML == imgtag2)
rgds.
Just check whether PLAY is present or not and then change innerHTML according to it
function changeimg()
{
var obj = document.getElementById('image1');
var imgtag1 = '<img src=\'PLAY.png\'>';
var imgtag2 = '<img src=\'PAUSE.png\'>';
if(obj.innerHTML.indexOf('PLAY') != -1)
{obj.innerHTML = imgtag2;}
else
{obj.innerHTML = imgtag1;}
return;
}

Categories

Resources