Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the JQuery to return a valid img src?

So, I have images in a div that share the same class and one of them is selected at a time for a single view of that image. In this single view, I have arrows that I want to use to cycle between the images. The images sharing the same class have sequential alt values.

Right now, I can get the preceding alt value and set the src of the image in the single view to the source of that image. But, I can't seem to get the same effect with the following image.

    $("#leftButton").click(function(){
            var current= $('img[id="selected"]');
            var altVal=current.attr("alt").valueOf()-1;
            if(altVal>=0)
            {
                var next= $('img[alt='+altVal+']');
                current.attr("id", "");
                next.attr("id", "selected");
                $("#embiggenImage").attr("src", next.attr("src"));
            }
        }
    );

    $("#rightButton").click(function(){
            var gal=$('img[class="galleryImage"]');
            alert(gal.length);
            var current= $('img[id="selected"]');
            var altVal=current.attr("alt").valueOf()+1;
            if(altVal<gal.length)
            {
                alert("inside");
                var next= $('img[alt='+altVal+']');
                current.attr("id", "");
                next.attr("id", "selected");
                $("#embiggenImage").attr("src", next.attr("src"));
            }
        }
    );

As you can see, the code for changing the sources is exactly the same, and it reaches those two alerts fine, but returns a null source.

Edit: It seems that in the leftButton click function, alt is being properly decremented, but in the rightButton click function, when I am trying to increment alt, it instead, is appending the '1', such that the final value of altVal is '01'. This does not make any sense to me..

like image 382
Anonymous Avatar asked Jan 01 '26 12:01

Anonymous


1 Answers

The problem is in the difference between these two lines:

var altVal=current.attr("alt").valueOf()-1;
var altVal=current.attr("alt").valueOf()+1;

- only has one meaning: subtract. If you call it on a string, it will be converted into a number before the operation.

+ has two meanings: add and concatenate. If you call it on a number, it adds. If you call it on a string, it concatenates. attr returns a string (as does valueOf -- I'm not sure what the point of that is), so +1 means "put add 1 to the end of the string".

You need to convert the value to a number instead. I'd use the unary + operator:

var altVal = +current.attr('alt') + 1;
like image 153
lonesomeday Avatar answered Jan 03 '26 03:01

lonesomeday



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!