JEP
JEP

Reputation: 23

Change CSS on a-tag when hash appears in URL

I have a fixed navigation bar with an a-tag that links to a hash-URL. When the a-tag is clicked the URL changes from url.com to url.com/#all and the page scrolls down to a div with the belonging id, while the navigation bar still appears as it is fixed.

What I want is to style the a-tag when the #all appears in the URL. All without refreshing the page. I guess it can be done quite simple with jQuery, but I'm not sure how.

To simplify what I want it is this:

Without #all in the URL:

<div style="position:fixed;height:50px;width:100%;"> <a href="#all">All</a> </div>

With #all in the URL:

<div style="position:fixed;height:50px;width:100%;"> <a href="#all" style="font-weight:700;">All</a> </div>

This also implies that when the #all is removed again from the URL the style should be removed as well - again, all without refreshing the page.

Upvotes: 0

Views: 1561

Answers (3)

Jeanne Chaudanson
Jeanne Chaudanson

Reputation: 131

So basically you want to change the style of the link once it has been clicked. That can be done easily with css:

a:visited {
    font-weight: 700;
}

I would advise giving a class or an id to your link though, so that the style doesn't apply to all of them!

If you reeeeally want to us jQuery, you can do something like this:

$('a').click(function() {
    $('a').css("font-weight", "700");
})

If you actually want to use the url, try :

if (window.location.href == 'http://url.com/#all')
    $('a').css("font-weight", "700");

My only concern is with the http/https, but that should be easily handled with an OR condition or some regex on the url variable to get a better substring.

Upvotes: 1

Red
Red

Reputation: 7324

You can get the # value from the url using just JavaScript

var id = window.location.hash.substr(1);

Now you have the value after the #, you can then use it as a selector.

So, for example;

/**
 * Lets say the URL looks like this:
 * https://example.com#all
 * var id contains now the value `all`
 */
var id = window.location.hash.substr(1);
    /**
     * Update id to valid css id selector
     * id is now `#all`
     */
    id = "#" + id;
/**
 * Get the element using the id we created above
 */
var elem = document.querySelectorAll('a[href="'+ id +'"]')[0];
    /**
     * You can also change the font weight using JavaScript
     */
    elem.style.fontWeight = "700";

See demo below;

/**
 * Lets say the URL looks like this:
 * https://example.com#all
 * var id contains now the value `all`
 */
var id = "all" //(Lets asume the value is `all`)window.location.hash.substr(1);
  /**
   * Update id to valid css id selector
   * id is now `#all`
   */
  id = "#" + id;
/**
 * Get the element using the id we created above
 */
var elem = document.querySelectorAll('a[href="'+ id +'"]')[0];
	/**
 	 * You can also change the font weight using JavaScript
 	 */
	elem.style.fontWeight = "700";
<a href="#all">TEST</a>

Upvotes: 1

Robert Williams
Robert Williams

Reputation: 1410

If you are using bootstrap then use built-in bootstrap scrollspy. Otherwise use this fiddle code to create your own. Modify the code as per need

// Cache selectors
var lastId,
    topMenu = $("#top-menu"),
    topMenuHeight = topMenu.outerHeight()+15,
    // All list items
    menuItems = topMenu.find("a"),
    // Anchors corresponding to menu items
    scrollItems = menuItems.map(function(){
      var item = $($(this).attr("href"));
      if (item.length) { return item; }
    });

// Bind click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e){
  var href = $(this).attr("href"),
      offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
  $('html, body').stop().animate({ 
      scrollTop: offsetTop
  }, 300);
  e.preventDefault();
});

// Bind to scroll
$(window).scroll(function(){
   // Get container scroll position
   var fromTop = $(this).scrollTop()+topMenuHeight;

   // Get id of current scroll item
   var cur = scrollItems.map(function(){
     if ($(this).offset().top < fromTop)
       return this;
   });
   // Get the id of the current element
   cur = cur[cur.length-1];
   var id = cur && cur.length ? cur[0].id : "";

   if (lastId !== id) {
       lastId = id;
       // Set/remove active class
       menuItems
         .parent().removeClass("active")
         .end().filter("[href='#"+id+"']").parent().addClass("active");
   }                   
});

Upvotes: 0

Related Questions