Issue
I have a function that takes 3 arguments: an image object, and the filenames of 2 images. The idea is that when the user clicks on it, it toggles the image. (This might be modified later to cycle through many images.)
The problem is that when you set the image's src field, it gets changed immediately. For example, I might do this:
image.src = "myimage.png";
And when I check it, I find that it contains the string "http://www.example.com/path/myimage.png"
. This is making it difficult to check whether it's currently showing image A or image B. What is the process that the browser goes through to modify this string, and is there a way that I can duplicate it in order to check which image is showing? (I'd rather not modify things to check the tails of the strings, since that would introduce some odd bugs when multiple images happen to have the same tails. It also seems to resolve ..
s intelligently, so just concatenating strings is likely a no-go.)
Thanks.
Solution
The value returned by HTMLImageElement.src
is the result of a URL normalization algorithm being applied to source URL. You can approximate this with a relative path using the following method:
const fullSrc = new URL('myimage.png', window.location.href).href;
If you want the raw strings, use Element.setAttribute()
/Element.getAttribute()
:
// Select and store image in variable
const img = document.querySelector('img');
// Store previous attribute value in a variable for subsequent use:
const oldSrc = img.getAttribute('src');
// Set new source attribute value:
img.setAttribute('src', 'myimage.png');
// Use previous value...
Answered By - jsejcksn Answer Checked By - David Goodson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.