The == is not working in my IF statement Function - javascript

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"
}

Related

How to assign Javascript Image object to existing Img element of JSP

JSP code is written as below,
< img src='<%=imageURL%>' id='advt-image-top' border='0' alt=''" /><br/>
Where the value of imageURL is like,
http://1.2.3.4:5678/ads/avw.php?zoneid=1234567890&cb=INSERT_RANDOM_NUMBER_HERE
(Sample URL which fetches random advertisement image from Ad-Server)
Now, same JSP page contains javascript-code like below:
$(document).ready(function() {
var imgAd = new Image();
imgAd.src = '<%=imageURL%>';
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
document.getElementById('advt-image-top').src='img/default_top.jpg';
}
}
}
Above javascript code checks - if image returned from ad-server is of size 1x1, then it should be replaced with default-image.
Problem is, above entire code-snippet executes "imageURL" twice in order to fetch one image from ad-server : one to check whether image-returned-from-ad-server is of size 1x1 and other during tag execution.
How can I optimize above code so that "imageURL" is executed only once?
How can I assign Image() object of javascript (after 1x1 validation is passed) to JSP's 'advt-image-top' element?
Thanks in advance.
You just need a minor adjustment to your javascript code, there is no need to create an Image:
$(document).ready(function() {
var imgAd = document.getElementById('advt-image-top');
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
imgAd.src='img/default_top.jpg';
}
}
}
However, the image might get loaded before the document ready fires and lose the onload event, so you might want to load the default url in your tag:
< img src='img/default_top.jpg' id='advt-image-top' border='0' alt=''" /><br/>
...and apply the remote url by code:
$(document).ready(function() {
var imgAd = document.getElementById('advt-image-top');
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
imgAd.src='img/default_top.jpg';
}
}
imgAd.src='<%=imageURL%>';
}
EDIT: probably the best way is to remove the img tag altogether from the jsp and write everything with javascript. Supposing that the image is contained in an element with id "container":
$(document).ready(function() {
var imgAd = new Image();
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
imgAd.src='img/default_top.jpg';
}
}
imgAd.src='<%=imageURL%>';
imgAd.id='adv-image-top';
imgAd.border=0;
document.getElementById('container').appendChild(imgAd);
}
#dipanda, Thanks for your comments. Helped me solve my problem.
var $imgObj = $("<img/>",{src:"<%=imageURL%>"});
$imgObj.load(function(){
var imgJS = $imgObj[0];
if(imgJS.height == 1 && imgJS.width == 1){
document.getElementById('advt-image-top').src='img/default_top.jpg';
}else{
if($("#advt-image-top")!=null && $("#advt-image-top")!=undefined){
$("container").append($imgObj);
}
}
};

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;
}

Javascript if/else statement using image src as condition

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';
}

Return address of image or error if it doesn't exist

I know my problem is the fact that I can't check if the image is good until it has time to load. I'm trying to check width and return after it or the src changes (using onerror to set an src.) I'm always getting stuck with a race condition though, and it errors out long before the height and width or src change. When I reload, the image is cached and it works fine. I don't know how to avoid this. Here is my current code (also not working, it loops until Firefox complains.) I'm setting the return of this function to a variable. There are some writes in there I'm using to see how far it gets, and it stops in the while loop. I tried using getTimeout('tstit = chkload("thisisatest",tinypth);',250);, but that didn't work either. I wish I could force this to load in order...
function buildimg(tehname,myc,pth1,pth2,tinypth)
{
var myimg = pth1+tehname+"/"+tehname+"-"+myc+".jpg";
buildtest("thisisatest",myimg,tinypth);
var testimg = document.getElementById("thisisatest");
var tstit = chkload("thisisatest",tinypth);
while(tstit == false) {
document.write(tstit);
tstit = chkload("thisisatest",tinypth);
}
alert(testimg.src+'-'+testimg.width+'-'+testimg.height);
if((testimage.width > 20) && (testimage.height > 20)) {
return myimg;
}
else if(typeof pth2 == "undefined") {
myimg = "error";
return myimg;
}
else {
myimg = buildimg(tehname,myc,pth2);
return myimg;
}
document.write('No return error in buildimg.');
return "error";
}
/*Builds a hidden img tag for testing images*/
function buildtest(itsid,itssrc,tinypath) {
if(document.getElementById(itsid)) {
var imgobj = document.getElementById(itsid);
imgobj.remove();
}
document.write('<img id="'+itsid+'" style="display: none;" src="'+itssrc+'" onerror="swaponerr(\''+itsid+'\',\''+tinypath+'\')" />');
}
/*Swaps the image to a small picture, so we can detect if it worked*/
function swaponerr(tagid, tinypath) {
var theimg = document.getElementById(tagid);
theimg.onerror = '';
theimg.src = tinypath;
}
/*Recurses to return when the image is loaded*/
function chkload(loadid,tinychk) {
var tehobj = document.getElementById(loadid);
document.write(tehobj.width+'x'+tehobj.height+'x'+tehobj.src);
if((tehobj.naturalWidth > 20) && (tehobj.naturalHeight > 20)) {
return true;
}
if(tehobj.src == tinychk) {
return true;
}
return false;
}
I need to test for an image, and return error if it is non-existent. The code below works fine on my server:
/*Checks if the image at /tehname/tehname-c.jpg exists in either of the paths
outputs it's address if it does, and "error" if not.*/
function buildimg(tehname,index,pth1,pth2)
{
var myimg = pth1+tehname+"/"+tehname+"-"+index+".jpg";
$.ajax({
url:myimg,
type:'HEAD',
error: function()
{
myimg=pth2+tehname+"/"+tehname+"-"+index+".jpg";
$.ajax({
url:myimg,
type:'HEAD',
error: function()
{
myimg="error";
return;
},
});
return;
},
});
return myimg;
}
Unfortunately, I'm trying to do this on a messed up system my work uses. We do have jquery, but the system stores user files on a separate server from code, so ajax won't work. This will eventually be in a .js file, I hope.
Now I've got code starting with:
function buildimg(tehname,myc,pth1,pth2)
{
var myimg = pth1+tehname+"/"+tehname+"-"+myc+".jpg";
var tehimage = new Image();
tehimg.src = myimg;
I tried to have the function load the image, and check its width, but I always get 0, since I can't pre-load the images without knowing how many they are (and I don't want to have some outrageously high number of requests with most being errors.) For some reason (at least on Firefox 4, as that's what my goal is to get working first) tehimage.complete always returns false. I've tried using onerror and onload by a global variable, and a few other methods. I must admit though, I'm not very versed in Javascript, so my callbacks may not have worked.
Please help, I'm getting desperate!
Do you hold the 'power to execute php code' on that user files server? If so, check them in php and output to images.js in that server, than in your html, first load images.js, then your usual javascript.
By the way, jQuery had memory leaks in ajax for ears, don't know about 1.6, but 1.5 definately had those. if you wan't to use ajax to get data from server to javascript - use plain javascript: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
Edit: Definately worth checking out: http://fettig.net/weblog/2005/11/28/how-to-make-xmlhttprequest-connections-to-another-server-in-your-domain/
Since I'm getting no answers, I'm closing the question. What I ended up doing was a modification to make the image change class in the onload, have the image onerror delete it, and have the rest of the code run in the window onload. Unfortunately, this means the 404s aren't caught before it tries to load more images, so I'm forced to limit the max number of images that can be used (changeable in the function call,) and the images that aren't there just waste a little time.
See the final result here.

Categories

Resources