Question

I want to replace "visual=true" with "visual=false" in each link that starts with "https://w.soundcloud.com/player/?url=". Is it possible? I want to force the embedded soundcloud players in my blog to change style (example:http://jsfiddle.net/gREY2/).

<iframe width="100%" height="450" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/84808541&amp;auto_play=false&amp;hide_related=false&amp;visual=true"></iframe>

Is there any way to do that with only jquery?

Was it helpful?

Solution

You can use txt.replace('search', 'replace') to perform String replace and txt.indexOf('search') to find if the string contains pattern you would like to search for.

This code should work for you:

$("iframe").each(function() {
    var src = $(this).attr('src');
    if(src.indexOf('https://w.soundcloud.com/player/?url=') != -1 && src.indexOf('visual=true') != -1) {
        $(this).attr('src', src.replace('visual=true', 'visual=false'));
    }
});

Because assigning new src actually reloads the iframe, hence creating another HTTP request I've added additional check if this action should be performed with && src.indexOf('visual=true') != -1. So it now only replaces the src whenever it's needed leaving other iframes untouched.

OTHER TIPS

Here's how do to it in pure JS:

var elements = document.getElementsByTagName('iframe');

for (var i = 0; i < elements.length; i++) {
    if(elements[i].src.indexOf('https://w.soundcloud.com/player/?url=') != -1 && elements[i].src.indexOf('visual=true') != -1) {
        elements[i].src = elements[i].src.replace("visual=true","visual=false");
        elements[i].contentWindow.location.reload();
    }
}

Be careful of elements[i].contentWindow.location.reload(); this may not work in all browsers. You'll also want to only run this after the DOM has loaded.

The following jQuery selector can be used to find all iframes that start with specified src:

$('iframe[src^=https\\3A \\/\\/w\\.soundcloud\\.com\\/player\\/\\?url\\=')

It may be better though just to see if the src attribute for iframe contains 'soundcloud', especially if you're not expecting other iframes to contain it:

$('iframe[src*=soundcloud')

Then you can replace the attribute with a string replace as per lokers's answer:

$('iframe[src*=soundcloud').each(function() {
    var src = $(this).attr('src');
    $(this).attr('src', src.replace('visual=true', 'visual=false'));
});

Please note that when the DOM initially loads, the iframe will send the request for the player with visual=true. You will then be re-loading it again with the new url, and you may see a flicker as it goes between the two different versions of the player. I'm assuming it isn't possible for you to change the URL in the HTML... but it would be much better if you did that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top