0

I'm creating dynamic image urls based on the user's screen size but how does one modify the url so that the screen size is added at the end?

The original url pattern:

http://abc.net/stakes-html/images/backgrounds/2560by1440/3.jpg
http://abc.net/stakes-html/images/backgrounds/2560by1440/abcr.jpg
http://abc.net/stakes-html/images/backgrounds/2560by1440/pkjg342.jpg

The final url:

http://abc.net/stakes-html/images/backgrounds/2560by1440/3-1240by768.jpg
http://abc.net/stakes-html/images/backgrounds/2560by1440/abcr-1240by768.jpg
http://abc.net/stakes-html/images/backgrounds/2560by1440/pkjg342-1240by768.jpg
1
  • 3
    It's just string manipulation. Iterate over all images you want to change, access their URL and (string) replace .jpg at the end of the string with -1240by768.jpg. However, not that it might make the browser (try load) load twice as many images. Example: stackoverflow.com/q/1029344/218196 Commented Apr 6, 2014 at 20:38

2 Answers 2

0

Assuming, images sizes are dynamically generated (like URL rewrite + image generator), You can always generate image paths dynamically, as follows:

'http://abc.net/stakes-html/images/backgrounds/2560by1440/3-' + window.innerWidth + 'x' + window.innerHeight + '.jpg'

and so on, where window.innerWidth is current window width in pixels and window.innerHeight is current window height in pixels.

Anyway, consider using Media Queries as they allows to show an image according to users resolution dynamically without javascript. Media Queries works in all major browsers right now.

Sign up to request clarification or add additional context in comments.

Comments

0
var index = url.lastIndexOf(".");
var newUrl = url.substring(0, index) + "-" + window.innerWidth + "by" + window.innerHeight + url.substring(index, url.length)
console.log(newUrl); //as you can see you have the new url with the size

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.