How can one (probably using the usual suspect Javascript), have a few (at first non-highlighted links) and then achieve:
Toggle on (make permanent) and off highlighting & differentiate between highlighting and redirect?
- Clicking on a term makes higlighting permanent (toggle on).
- Clicking again (after toggle on) on that term redirects to article.
- Clicking elsewhere removes higlighting (toggle off).
EDIT (to clarify, after question had been put on hold):
Toggle highlighting
I understand this highlighting can be handled using .addClass("active");
and .removeClass("active");
, but have no clue on how to include the links when the Class("active")
is added and/or how to disable the links when that Class
is removed. CSS would then need (e.g.) .active{background:green}
Toggle redirect (link follow)
- So, it is now figured out
preventDefault();
plays a central role in enabling or disabling link following; since, as one can read in its entry in the jQuery-api:
- If this method is called, the default action of the event will not be triggered.
- For example, clicked anchors will not take the browser to a new URL.
- Another way to do this might be using
return false;
.
The difference between the 2 has to do with propagating (or
"bubbling up") the
DOM. About
this difference, one can read at
CSS-tricks
or have a look at the answer below by
somethinghere,
when he adds event.stopImmediatePropagation();
to stop this
bubbling up
The difference between the two is the following: return false;
also prevents this propagation by itself, whereas preventDefault();
doesn't.
The CSS-tricks-article sais:
function() {return false;}
Is equal to:
function(e) {e.preventDefault(); e.stopPropagation();}
More literature about the difference can be found on StackExchange, which might feature some duplicate posts?
- What's the difference between e.preventDefault(); and return false?,
- event.preventDefault() vs. return false,
- event.preventDefault() vs. return false (no jQuery),
- Difference - "e.preventDefault();" and "return false;".
var anchors = document.getElementsByTagName('a'),
length = anchors.length,
index;
for (index = 0; index < length; index += 1) {
anchors[index].onclick = function (e) {
e.preventDefault();
if (!(/\bhighlight\b/).test(e.target.className)) {
e.target.className += ' highlight';
}
};
}
.blockElement {
display:block;
float: left;
clear: left;
}
.highlight {
background-color: yellow;
}
<a href="#one" class="blockElement">Jump to One</a>
<a href="#two" class="blockElement">Jump to Two</a>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<div id="one">One</div>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<div id="two">Two</div>