Adam Adam - 3 months ago 11
jQuery Question

Injection text into "URL" part of img tag

I have a URL like this: http://website.com/~user/wordpress_site/wp-content/uploads/2016/08/logo.png

What I want to do is that when the screen is smaller than 768px wide, I can change the url so instead of "logo.png" it says "mobile-logo.png".

Is there a function similar to "PHP explode" where I can target the logo part and replace it with "mobile-logo"?

The problem is the URL is dynamic so if I for example, say that I want to add the word "mobile" in after 10 characters, it may not work as url will change so it puts it in the wrong place.

Is there a bit of javascript/jQuery to simply do this?
Many Thanks

Answer

You can do this with css. Just use two <img> for this issue, like this:

HTML:

<img class="show-on-desktop" src="http://website.com/~user/wordpress_site/wp-content/uploads/2016/08/logo.png" />
<img class="show-on-mobile" src="http://website.com/~user/wordpress_site/wp-content/uploads/2016/08/mobile-logo.png" />

CSS:

.show-on-mobile{
    display: none;
}

@media only screen and (max-width: 768px){
    .show-on-desktop{
        display: none;
    }

    .show-on-mobile{
        display: block;
    }
}

Working example: https://jsfiddle.net/5kb6ndsp/

Comments