How to Get Jquery or JavaScript to Change CSS Based on the Current Url

How can I get jQuery or Javascript to change css based on the current url?

In your situation, you could try something like this:

$("A").each(function () {
if (this.href == document.URL) {
$(this).addClass('active');
}
});

That checks for every link if the href attribute matches the current documents URL, and if it does add class 'active' to the elements CSS classes.

A small caveat: this will only work if the absolute URL referred to in the menu and used in the actual document match exactly.
So let's say the current URL is http://example.org/dir/, then <a href="index.html"> will not be highlighted, since it resolves to http://example.org/dir/index.html. <a href="/dir/"> will match.

(Making sure the same URL is used for each page throughout the site is good practice anyway, e.g. for search engine optimization and caching proxies)

The different parts used are:

  • $("A") selects all A elements (anchors). You'll probably want to make it a bit more specific by selecting all A elements within your menu, e.g. $("#menu A"). [jQuery]
  • .each(func) executes the specified function on each of selected elements. Within that function this will refer to the selected element. [jQuery]
  • this.href returns the absolute URI of the linked resource, not, as you might expect, the possibly relative location specified in the HTML. [standard DOM]
  • $(this).addClass(clzName) is used to add a CSS-class to the specified element. [jQuery]

To make sure $("A") finds all elements, execute it after the document is fully loaded (in the $(document).ready() jQuery event-handler, or using the onload attribute of the BODY tag).

Changing CSS for link of current page with jQuery

window.location.href will get your current URL. Then you need to use a jQuery selector that finds the <span class="main-nav-item"> child of the <a class="main-nav-link"> element with that href attribute. Apply your class "current" to that element, and you should be good to go. So how about this JavaScript:

// Get the current URL
var currentUrl = window.location.href;

// Get the span you want with a combination class and attribute and child jQuery selector
var currentMenuItem = $(".main-nav-link[href='" + currentUrl + "'] > .main-nav-item");

// Then add your class
currentMenuItem.addClass("current");

Put that in your script tags and give it a try.

Once you have it working, make sure you add the proper CSS rules. For example, add a rule that loads a different background image for #nav-content.current (and another all the rest).

(A note about your current CSS: It looks like you're overqualifying your selectors. If you don't have to worry about .main-nav-items anywhere else on the page, don't bother qualifying that class with the .main-nav before it. And your id selectors (e.g. #nav-content) certainly don't need to be qualified, since they're unique identifiers.)

Hope that makes sense to you and helps.

Javascript/jquery change css depending on url

This will get your hash value you and load it. If you are changing the # at runtime, you will need to make sure you delete the previous, but this is assuming you will just do this once.

var hash_var = window.location.hash;
if (hash_var){
$("<link />").attr({
rel:"styleheet",
type:"text/css",
href:hash_var.substring(1) + ".css"
}).appendTo("head");
}

Change CSS with JS / jQuery when hash value in URL changes

Without having a working example, I believe the issue is within this line:

window.addEventListener("hashchange", locationChange(), false);

Adding a listener is a right course of action, but you are calling your function when you are defining the listener. Changing locationChange() to locationChange will not immediately invoke the function and instead pass a handle to the function:

function locationChange() {
if(location.hash == "#1") {
$('#list-item-1').css('background-color', '#333333');
$('#list-item-2').css('background-color', '#333333');
} else {
$('#list-item-1').css('background-color', '#ffffff');
$('#list-item-2').css('background-color', '#ffffff');
}
);
window.addEventListener("hashchange", locationChange, false);

change url using jquery for specific css classes

What you want to do is first define the parent class and then for that class select all the link elements.

In jQuery you can use multiple selectors that works as follows:

$("#test")          // select div 'test'
$(".myClass") // select class 'myClass'
$(".myClass #test") // select div 'test' in class 'myClass'
$("a") // select all link elements

Therefore, what you need is the following: $(".testclass a") which selects all link elements in the class .testclass. Then you can use jQuery .each() function to do something with the link elements.

$( document ).ready(function() {
$(".testclass a").each(function() {
var value = $(this).attr('href');
alert(value);
});
});

jsFiddle

Change CSS styling with javascript depending on page

Use jquery to hide the div if there's nothing in it.

if($('#FloatLeft').html() == ''){
$('#FloatLeft').remove();
}

This will only work assuming your next and previous buttons post back to the server. If all your content is static, then use this instead:

//this requires you change the css classes like I explain below

$('.searchButton').on('click',function(){

if($('#FloatLeft').html() == ''){
$('#left').css('display','none');
} else {
$('#FloatLeft').css('display','block');
}

}

edit

p.s.

Why do you have two css classes that do the same thing? Clean that up to one for readability. If you created two because the second element wasn't having styles applied to it, that's because you used id instead of class. id is unique, and will only target the first element it matches with that id. # is used for id, . is used for class.

.searchButton {
color: white;
background-color: #3498db;
padding: 10px;
padding-right: 20px;
}

<div class="FloatLeft searchButton"></div>
<div class="FloatRight searchButton"> <a> whatever </a> </div>

how to detect a url path with jquery and change css

Not with jQuery per se, but you can just use window.location.pathname.

if (window.location.pathname.indexOf('page') > 0) {
$("#splash").hide();
}

How to change css property of content:url in jquery?

Try ...

$(document).ready(function(){
$("#arrow").click(function(){
$("#p1").attr({style: "content:url(images/cerchioSelezionato.png)" });
$("#p0").attr({style: "content:url(images/cerchio.png)" });
}
}

You're changing the Style attribute, but the content attribute.

How to live update CSS based on screen size, using JQuery?

Additionally to the ready Callback function you can also use jquery.resize. You just have to execute the same code on the resize callback. Resize will be called every time the window size changes.

For the sake of less code redundancy I introduced a new method adjustContent:

$(document).ready(adjustContent);

$(window).resize(adjustContent);

function adjustContent() {
var contentPlacement = $('#topMenu').position().top + $('#topMenu').height();
$('body').css('margin-top',contentPlacement);
$('#navWindow, #searchWindow').css('margin-top',-contentPlacement);
}


Related Topics



Leave a reply



Submit