I have these links:
<a class="active" href="#section1">Link 1</a>
Link 2
When a link 2 is clicked I would like it to receive the active class and remove the class from link 1 itself so it would effectively become:
Link 1
<a class="active" href="#section2">Link 2</a>
This should work both ways. Ie. whatever link is clicked gets the class and removes it from the other.
How can this be done with JavaScript/Prototype?
Try this:
// initialization
var links = document.links;
for (var i=0; i<links.length; ++i) {
links[i].onclick = function() {
setActive(links, this);
};
}
function setActive(links, activeLink) {
for (var i=0; i<links.length; ++i) {
var currentLink = links[i];
if (currentLink === activeLink) {
currentLink.className += " active";
} else {
currentLink.className = currentLink.className.split(/\s+/).map(function(val) {
return val === "active" ? "" : val;
}).join(" ");
}
}
}
You could write a little helper function with prototype support that removes the class from all active elements and adds it to the one that was clicked on:
function active(e) {
$$('.active').each(function(i) {
i.removeClassName('active');
});
e.addClassName('active');
};
You can than call this function from your onclick events:
a
b
c
If it were jQuery, I would do it like
$(document).ready(
function(){
$("a").click(function(){
$("a").toggleClass("active");
});
}
)
Related
I can't seem to figure out how to make my site navigation have an active link for the current page.
This is the only code that is working for me, however, there is always two links with the class "active." I only want the current page to be active.
Here is my code:
<script>
function setActive() {
aObj = document.getElementById('nav').getElementsByTagName('a');
for(i=0;i<aObj.length;i++) {
if(document.location.href.indexOf(aObj[i].href)>=0) {
aObj[i].className='active';
}
}
}
window.onload = setActive;
</script>
Here is my staging site: http://champhero.wpengine.com
Thanks for any help!
You are checking an indexOf. Therefore, URL http://champhero.wpengine.com/ is always contained in others like http://champhero.wpengine.com/the-enemies/
If you just check an equality, it should work:
function setActive() {
var aObj = document.getElementById('nav').getElementsByTagName('a');
for (var i = 0; i < aObj.length; i++) {
if (document.location.href == aObj[i].href) {
aObj[i].className = 'active';
}
}
}
Note: You were not declaring local variables with 'var', making them globals and potentially unstable across the environment. i changed that in my suggested code.
a tag href contains whole link so you could check for equality like below.
<script>
function setActive() {
aObj = document.getElementById('nav').getElementsByTagName('a');
for(i=0;i<aObj.length;i++) {
if(document.location.href === aObj[i].href) {
aObj[i].className='active';
}
}
}
window.onload = setActive;
</script>
Home page nav link(http://champhero.wpengine.com/) is highlighted in every page because it's present in all other links(http://champhero.wpengine.com/pagelink)
<script>
window.onload = function(){
var anchors = document.getElementsByTagName('a');
for (var i = 0; i < anchors.length; ++i)
if (anchors[i].href === window.location.href)
anchors[i].className += ' active';
};
</script>
though this snippet will apply the class to all anchors. For just the ones in, say, your navigation bar, give them a specific CSS class to hook into and then:
<script>
window.onload = function(){
var nav_links = document.querySelectorAll('.nav-link');
for (var i = 0; i < nav_links.length; ++i)
if (nav_links[i].href === window.location.href)
nav_links[i].className += ' active';
};
</script>
So I have a list of elements in an array. I'd like to add a jQuery toggle event to each element and pass in two functions as parameters. This is what I have so far, though it's giving me errors, saying that e (the Event Object) is undefined inside moveToSelected and moveToUnselected.
// Getting my array
var selected = document.getElementsByClassName("selected_style");
// The two functions to toggle between:
function moveToSelected(e) {
style = e.target;
style.className = "selected_style";
$('#selected-style').append(e.target);
}
function moveToUnselected(e) {
style = e.target
style.className = "unselected_style";
$('#unselected-style').append(e.target);
}
// Going through the array and adding a toggle event to each element.
for(var i = 0; i < selected.length; i++) {
var element = $(unselected[i]);
element.toggle(moveToSelected, moveToUnselected);
}
HTML, as requested:
<ul id="selected-style">
<li>
Some Style
</li>
<li class="selected_style">
Style
</li>
<li class="selected_style">
Style
</li>
<li class="selected_style">
Style
</li>
</ul>
Thanks for the help!
Uhm, why aren't you using jQuery, this is already built in ?
$('.selected_style').on('click', function() {
$(this).toggleClass('selected_style unselected_style');
if ( $(this).hasClass('selected_style') ) {
$('#selected-style').append(this);
} else {
$('#unselected-style').append(this);
}
});
FIDDLE
The vanilla javascript solution for future viewers. No jQuery required. This is effectively the same script as the accepted answer, without all the overhead of jQuery.
(Demo)
(function () {
"use strict";
var selected = document.getElementById('selected-style');
var unselected = document.getElementById('unselected-style');
var items = document.querySelectorAll('.selected_style'), item;
for (var i = 0; item = items[i]; i++) {
item.onclick = function(){
if(this.className.indexOf('unselected_style') >= 0) {
this.className = this.className.replace(' unselected_style','');
this.className += ' selected_style';
selected.appendChild(this);
} else {
this.className = this.className.replace(' selected_style','');
this.className += ' unselected_style';
unselected.appendChild(this);
}
};
}
})();
I have a list of JQM, and a button for each instance on a list.
When click on the button I call to function ...
function xxx()
{
alert ('click on me!! :]');
}
Clicking on the button Not triggering the function, why?
Look at the following jsFiddle: http://jsfiddle.net/Hodaya/nR369/3/
To bind the xxx function to the click event of the newLI DOM element you should either use the newLI.onclick=xxx; or better yet use jQuery to do the binding with $(newLI).click(xxx);
Finally the problem is resolved:
Pressing the button did not work because:
to each button on the list was the same id ,In the moment I added a unique name for each of the buttons, it worked.
Here the code:
for (var i = 0; i < Local.length; i++) {
newLI.innerHTML = '<a href="to.html" data-transition="slide" dir="rtl" onclick="YYY();" >' +
'<p>...'</p>' +
'<a id="btnClearOneBookmark' + i + '" data-role="button" data-icon="delete" data-theme="b"></a>' +
' </a>';
$("#btnClearOneBookmark" + i).click(function () { xxx(); });
}
Try this:
$("#mybutton").on('click',function() {
var ul = document.getElementById("bookMarkMenu");
for (var i = 0; i < 5; i++) {
var newLI = document.createElement("LI");
console.log(i)
newLI.innerHTML = '<p>...</p>' +'<a id="btnClearOneBookmark" data-theme="b" data-role = "button"></a>';
newLI.setAttribute('data-theme', 'c');
newLI.setAttribute('onclick', 'DisplayBookMark()');
ul.appendChild(newLI);
$('ul').listview('refresh');
}
});
$("#btnClearOneBookmark").live('click',function() {
alert("click on me!! :]");
});
I'm trying to detect if certain element is clicked on onbeforeunload. I can't get it to work. Below is examples of the Javascript code and HTML code on the project (Please note that I have no control over the HTML element as it is not my site)
function checkLeave() {
var p = document.getElementByElementById('yeah');
if (p.href.onclick) {
//do something
}
else {
//do something else
}
}
window.onbeforeunload = checkLeave;
HTML CODE
//The goSomewhere goes to another page
<a id="yeah" href="javascript:goSomewhere();">
<img src="smiley.png">
</a>
Thanks in advance,
J
What you need to do is bind an event handler to each on the page.
This can be done with the following:
// Select all links
//var allLinks = document.querySelectorAll('a[href]');
var allLinks = document.links;
// Bind the event handler to each link individually
for (var i = 0, n = allLinks.length; i < n; i++) {
//allLinks[i].addEventListener('click', function (event) {});
allLinks[i].onclick = function () {
// Do something
};
}
You are testing for the presence of the onclick property to the <a> tag. It isn't present in the markup. Rather than using the onclick, the markup calls a script as the element's href. So you need to look for a script in the href instead:
var p = document.getElementByElementById('yeah');
if (p.href.indexOf("javascript") === 0) {
//do something
}
else {
// do something else
}
Maybe something like this? (just the idea)
document.getElementById('yeah').onclick = function() {
clicked = this.href;
};
I'm trying to create a tab menu. And I need this coded in regular javascript, not jquery.
$(document).ready(function() {
//When page loads...
$(".general_info_content").hide(); //Hide all content
$("ul.general_info_tabs li:first").addClass("active").show(); //Activate first tab
$(".general_info_content:first").show(); //Show first tab content
//On Click Event
$("ul.general_info_tabs li").click(function() {
$("ul.general_info_tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".general_info_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active ID content
return false;
});
});
The core of what you want to do is below - I'm sure there are a thousand different ways to do each task:
Remove a CSS class from an element:
var classes = document.getElementById([id]).className.split(" ");
for(var i = 0; i < classes.length; i++)
if(classes[i] == removeClass)
classes[i] = "";
document.getElementById([id]).className = classes.join(" ");
Add a CSS class to an element:
document.getElementById([i]).className += " " + addClassName;
Hide an element:
document.getElementById([i]).style.display = "none";
Fade an element:
// not tested, but based on tested/used code
function fade(el, opacity, fadeInTime) {
if (opacity < 100) {
el.style.opacity = opacity / 100;
el.style.filter = "alpha(opacity=" + opacity + ")";
opacity += 5;
setTimeout(function () { fade(el, opacity, fadeInTime); }, fadeInTime / 5);
}
}
To find all elements by CSS and tag name:
var matches = new Array();
var all = document.getElementByTagName(searchTagName);
for(var i = 0; i < all.length; i++){
if(all[i].className.replace(searchClassName, "") != all[i].className) {
matches.push(all[i].className);
}
}
// do something with (i.e., return or process) matches
And for the record, I find it encouraging, not unreasonable, that a person using the jQuery library wants to know how to do get things done with native JS/DOM.
More functions to complement Brian's post. Good luck.
EDIT: As I mentioned I would change the class=general_info_content to id=general_info_content1.
function attach(el, event, fnc) {
//attach event to the element
if (el.addEventListener) {
el.addEventListener(event, fnc, false);
}
else if (document.attachEvent) {
el["on" + event] = fnc; // Don not use attachEvent as it breaks 'this'
}
}
function ready() {
// put all your code within $(function(){}); here.
}
function init() {
attach(document, "readystatechange", function () {
if (document.readyState == "complete") {
ready();
}
});
}