Skip to content Skip to sidebar Skip to footer

Class Of Id Change Based On Url - Url Based Image Swap -

What I'm trying to achieve: Based on URL (ie., foo.com/item1), the div element 'logoswap' receives a different class. The following is the code I put together but it seems complete

Solution 1:

Assigning CSS Class By URL Pathname

A jsfiddle has been setup for this solution.

Here is a case for using numeric expressions if they are available. This does not apply to the above question.

$(function() {
  var rgx = /item(\d+)$/,
      url = location.pathname,
      id = (rgx.test(url)) ? url.match(rgx)[1] : '1';
  $("#logoswap").addClass("class" + id);
});

UPDATE:

In light of the new details you may need an array of values, these should be derived from or exactly equal to the class names you intend to use.

$(function(){
  // my favorite way to make string arrays.var matches = "brand1 brand2 brand3".split(" "),
      url = location.pathname.match(/\w+$/)[0], // get the last item
      id = matches.indexOf(url),
      className = matches[(id > -1) ? id : 0];
  $("#logoswap").addClass(className);
});

To make this work you will need a few things in place. I will assume that the paths will end in a number as we have outlined here. The default ends with 1. You will need the images to be accessible. You need to define the styles for each possibility.


CSS Setup

#logoswap {
  height : 200px;
  width : 200px;
}
.class1 {
  background-image : url(/path/to/default.jpg);
}
.class2 {
  background-image : url(/path/to/second.jpg);
}
.brand1 {
  background-image : url(/path/to/brand/1/logo.jpg);
}
...

Without jQuery

if you do not have jQuery in your code you may need to use window.onload.

(function(){
  var old = window.onload;
  window.onload = function(){
    old();
    var r = /item(\d+)$/,
        url = location.pathname,
        id = (r.test(url)) ? url.match(r)[1] : '1';
    document.getElementById('logoswap').className += "class" + id;
  };
})()

I just want to take a moment here to encourage anyone who is doing this type of code to get used to Regular Expressions and learn them. They are far and away the most frequently used cross language part of my development arsenal.

Solution 2:

There's nothing that wrong with what you have. You could tidy it up with something like below.

$(function() {
    var url = location.pathname;
    var logo = document.getElementById("logoswap");
    var i = 6;

    logo.className = "class1";

    while(i--)
    {
        if(url.indexOf("item" + i) > -1) {
            logo.className = "class" + i;
        }
    }
});

Hope this helps.

Solution 3:

Using just HTML/CSS, you could add (or append via javascript) an id to the body of the page:

<body id="item1">

Then in your CSS, create a selector:

#item1#logoswap {
    // class1 CSS
}

Post a Comment for "Class Of Id Change Based On Url - Url Based Image Swap -"