skip to Main Content

I want to change the image in a div based on the redirect URL of a page.

If the redirect URL contains "mens" then show image a, if url contains "womens" show image b.

the URL looks like this
https://mydomainname.com/login/?redirect_to=https%3A%2F%2Fmydomainname.com%2Fwomens%2F

var urlParts = document.URL.split("/");
lastPart = urlParts[urlParts.length-1] == '' ? urlParts[urlParts.length-2] : urlParts[urlParts.length-1];Object

if(lastPrt == 'some_page_or_url_name') {
$("#logo").attr('src', 'path_to_image');
}

I also tried this

var URLChar = location.href.substring(location.href.length - 12, location.href.length);

if (URLChar === "womens"){
    image.src = "../MCFILES/NSW1.jpg";
} else if (URLChar === "mens"){
    image.src = "https://mydomainname.com/wp-content/uploads/2023/04/BackPatch_600x600_compressed.webp";
};

2

Answers


  1. I would consider avoiding parsing the path unless you must. Does something like below work as expected?

    `if (window.location.pathname.includes('women')) {
        image.src = 'women-url';
    } else {
        image.src = 'men-url';
    }`
    
    Login or Signup to reply.
  2. I would do this a bit differently. Take a look at this code:

    // Get the redirect URL from the current page
    var redirectURL = decodeURIComponent(window.location.href);
    
    // Check if the redirect URL contains "mens"
    if (redirectURL.includes("mens")) {
      // Show image a
      $("#logo").attr('src', 'path_to_image_a');
    } 
    // Check if the redirect URL contains "womens"
    else if (redirectURL.includes("womens")) {
      // Show image b
      $("#logo").attr('src', 'path_to_image_b');
    }
    

    In the code above, we use jQuery to select the image element with the ID "logo" using $("#logo"). Then, we update the src attribute of the selected image using the attr() function based on the redirect URL.

    Replace ‘path_to_image_a’ and ‘path_to_image_b’ with the actual paths to your images. Additionally, make sure that the HTML contains an image tag with the ID "logo" (<img id="logo" src="">).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search