web hosting
build a website

Amending HTML/ CSS in JavaScript for a specific URL

Mar 23, 2014   //   by Anthony Devine   //   Website Development tips  //  No Comments

I have already added a post about amending html in JavaScript based on a page title, however if you need to change the HTML/CSS based on a URL then you can use the following.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$.noConflict();
jQuery(document).ready(function($) {
var url = window.location.href;
if(url == "http://www.webaddress.com/sale?p=1") {
    $(".nonproductcatimage2").append('<style>.nonproductcatimage2{display:none;}</style>');
	$(".nonproductcatimage3").append('<style>.nonproductcatimage3{display:none;}</style>');
}
else if(url == "http://www.webaddress.com/sale?p=2") {
    $(".nonproductcatimage1").append('<style>.nonproductcatimage1{display:none;}</style>');
	$(".nonproductcatimage3").append('<style>.nonproductcatimage3{display:none;}</style>');
}
else if(url == "http://www.webaddress.com/sale?p=3") {
    $(".nonproductcatimage1").append('<style>.nonproductcatimage1{display:none;}</style>');
	$(".nonproductcatimage2").append('<style>.nonproductcatimage2{display:none;}</style>');
}
else{
    $(".nonproductcatimage2").append('<style>.nonproductcatimage2{display:none;}</style>');
	$(".nonproductcatimage3").append('<style>.nonproductcatimage3{display:none;}</style>');
}
});
</script>


<div class="nonproductcatimage1" style="position:absolute;top: 326px;left: 850px;z-index:99;"><img src="cat-image-non-product1.jpg" alt="offer1"></div>

<div class="nonproductcatimage2" style="position:absolute;top: 682px;left: 677px;z-index:99;"><img src="cat-image-non-product2.jpg" alt="offer1"></div>

<div class="nonproductcatimage3" style="position:absolute;top: 327px;left: 322px;z-index:99;"><img src="cat-image-non-product3.jpg" alt="offer1"></div>

This basically uses an if statement to say, if the URL is http://www.webaddress.com/sale?p=1 then hide the 2 div elements, or if the URL is http://www.webaddress.com/sale?p=2 or http://www.webaddress.com/sale?p=3 then do something else and if the URL is none of those then it uses the else statement.