PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 29, 2022

[FIXED] What happens to an img's src after you set it?

 July 29, 2022     html, image, javascript     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing