how to change an image src from another page

Asked

Viewed 161 times

1

Hello, I have an input where it serves as a search bar. By entering a name and pressing enter, a function is activated and performs the following function:

function verificaValor(){
   var valor = $('#search').val();
   switch (valor) {   
      case "scripts":
        window.location.href = 'scripts.html';
        document.getElementById("imgDinamica").src="Slide1.png";
      break;

When typing scripts it goes to another page, but does not change the image. How do I change the image of another page?

1 answer

3


You can do it using only Javascript if that’s what you want. I’d do it like this:

In place of that line of yours:

window.location.href = 'scripts.html?imagem=Slide1';

And on the page scripts.html, somewhere afterward where that imgDinamica appears:

/// copiado de http://stackoverflow.com/a/901144
function getParameterByName(name, url) {
    if (!url) {
      url = window.location.href;
    }
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

var imagem = getParameterByName('imagem');
if (imagem !== null) {
    document.getElementById("imgDinamica").src = imagem + ".png";
}
  • Perfect! Thank you so much! You have no idea how you helped me. ^^

  • You’re welcome, @Guilhermes.Santos! I’m very happy to help, and even more so when they come back to thank you and say it was useful.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.