Making Links Active in JavaScript

Making links active in Javascript

Since you're just starting out, I'd suggest you use a library such as jQuery. So, if your HTML is like this:

<div id="box1" class="box">
<h3><a name="box1">something</a></h3>
</div>
<div id="box2" class="box">
<h3><a name="box2">something</a></h3>
</div>
<div id="box3" class="box">
<h3><a name="box3">something</a></h3>
</div>

And you have a CSS class called youarehere:

.youarehere { color:white; background:green; }

With jQuery you could write something along the lines of:

$(".box > a").click(function() {             // when clicking any of these links
$(".box > a").removeClass("youarehere"); // remove highlight from all links
$(this).addClass("youarehere"); // add highlight to clicked link
})

In plain JS, it takes a bit more effort to achieve this. Do yourself a favor and don't reinvent the wheel - people have already taken care of this, so use the product of their labor to make your life easier.

Making links clickable in Javascript?

Yes. The simplest way is to use a regular expressions to substitute things that look like a link for their linked equivalents. Something like:

node.innerHTML = node.innerHTML.replace(/(http:\/\/[^\s]+)/g, "<a href='$1'>$1</a>")

(my RegEx is a little rusty, so you may need to play with the syntax). This is just a simple case. You need to be wary of script injection here (for example if I have http://"><script>doevil()</script>). One way to work around this is by using a link building function:

node.innerHTML = node.innerHTML.replace(/ ... /g, buildLink($1));

Where buildLink() can check to make sure the URL doesn't contain anything malicious.

However, the RegEx-innerHTML method will not perform very well on large bodies of text though, since it tears down and rebuilds the entire HTML content of the node. You can achieve this with DOM methods as well:

  • Find reference to the text node
  • In the content, find start and end indexes of a URL
  • Use splitText() method to split the node into 3: before, link, after
  • Create an <a> node with the href that's the same as the link
  • Use insertBefore() to insert this <a> node before the link
  • Use appendChild() to move the link into the <a> node

How to change a link to active state using an onclick function in javascript

One way that you could do it would be to make use of the browser's localStorage - If you modify the above playersidenav.php slightly by removing the inline event handler like this and then including some Javascript within this file so that it looks like this:

<div class="column sidenav">
<div class="row">
<img src="../images/avatar.png" alt="Avatar">
<h1 style="color:white;float:right;padding-top:7%">Hello John!</h1>
</div>
<a class="normal" href="news.php">NEWS</a>
<a class="normal" href="schedule.php">SCHEDULE</a>
<a class="normal" href="partners.php">PARTNERS</a>
<a class="normal" href="coaches.php">COACHES</a>
<a class="normal" href="tournaments.php">TOURNAMENTS</a>
<a class="normal" href="events.php">EVENTS</a>
<a class="normal" href="shops.php">SHOPS</a>
</div>
<script>
//The name of the store in localStorage
const store='LINK_ACTIVATED_MEMORY';

// the class to add to indicate active state
const cn='active';

// nodelist of all sidenav links
const links=document.querySelectorAll('.sidenav > a.normal');

// ensure any "active" links have class removed and then
// save new hyperlink to localStorage
const makeActive=(e)=>{
e.preventDefault();
links.forEach(a=>a.classList.remove(cn));
localStorage.setItem( store, e.target.href );
location.href=e.target.href;
};

// on page load run this function - check the store
// and iterate through nodelist to match saved value and
// node value.
const loadActive=()=>{
let stored=localStorage.getItem( store );
if( stored==null )return;

Array.from( links ).some(a=>{
if( stored==a.href ){
a.classList.add(cn)
return true;
}
});
};

//bind the event handler
links.forEach(a=>a.addEventListener('click',makeActive));

// load active link class
loadActive();

</script>

The link that is clicked will be stored in localStorage and then when the new page is loaded the loadActive function will be invoked to set the active class. As per the comment by @Kiko Software - the default action when clicking a hyperlink would mask any highlighting attempt anyway so the actual setting of the class should be done on page load/reload.

After thinking about the suggestion by @Kiko Software that this could be done with PHP and dispense with Javascript altogether I wrote that as an alternative solution.

The included file playersidenav.php:

<?php

$cn='active';

$links=array(
'home.php' => 'TEST PAGE HOME',
'news.php' => 'NEWS',
'schedule.php' => 'SCHEDULE',
'partners.php' => 'PARTNERS',
'coaches.php' => 'COACHES',
'tournaments.php' => 'TOURNAMENTS',
'events.php' => 'EVENTS',
'shops.php' => 'SHOPS'
);
?>

<div class="column sidenav">
<div class="row">
<img src="../images/avatar.png" alt="Avatar" />
<h1 style="color:white; float:right; padding-top:7%">Hello John!</h1>
</div>
<?php
foreach( $links as $href => $text ){
printf(
'<a href="%s" class="normal %s">%s</a>',
$href,
( basename( $_SERVER['SCRIPT_FILENAME'] )==$href ? $cn : '' ),
$text
);
}
?>
</div>

And an example page calling said file, called home.php:

<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<style>
.sidenav a.active {
background-color: #001F5A;
color: white;
border-radius: 5px;
}
a{margin:1rem;}
</style>
</head>
<body>

<?php
require sprintf('%s/playersidenav.php',__DIR__);
?>

<h1>Hello World!</h1>
</body>
</html>

The PHP include file compares the array key to the basename from the current SCRIPT_FILENAME server variable and adds the class accordingly and negates the need for Javascript completely. Just proves the old saying - "There's more than one way to skin a cat"

Active Link Using Javascript

Trim the end slash(/) using Regex.

    var current = location.pathname.replace(/\/+$/, "");    console.log(current);

How to add active class on link click

If you change all of your Links to NavLinks then you can add an active class automatically.

<NavLink to='/home' activeClassName="active_class_link">Dashboard</Link>

Active link after click

Thanks to @Panther this is easier than i tought:

$(document).ready( function(){
var location = window.location.pathname;
location = location.replace("/", "");
$("a[href='"+location+"']").addClass("active");
});

How to change active color of hyperlink with javascript?

You can set an ID on the link and target that with the css

#my-id {color: blue}
#my-id:active {color: red}

Make navbar link active on wheel event rather than scroll?

Try using an IntersectionObserver instead:

const navLinks = document.querySelectorAll("nav a");

const updateNav = (entries, observer) => {
const matchingIds = entries.filter(e => e.isIntersecting).map(e => `#${e.target.id}`);

if (matchingIds.length !== 0) {
const current = matchingIds[0];
navLinks.forEach(function(link) {
link.classList.remove("nav-active");
if (link.getAttribute("href") == current) {
link.classList.add("nav-active");
}
});
}
};

const options = {
root: null,
rootMargin: "0px",
threshold: 0.66
}

const observer = new IntersectionObserver(updateNav, options);
document.querySelectorAll("*[data-scroll-section]").forEach(el => observer.observe(el));

Intersection Observer API

Demo



Related Topics



Leave a reply



Submit