Use JavaScript to change the class of an <li> - javascript

I have the following code:
<div id="nav">
<ul>
<li id="tabOne" class="first current">Page One</li>
<li id="tabTwo">Page Two</li>
<li id="tabThree"><a href="./CS3.html" target="SheetView">Page Three</li>
<li id="tabFour">Page Four</li>
<li id="tabFive">Page Five</li>
<li id="tabSix">Page Six</li>
</ul>
This loads the selected page into an iframe named "SheetView." What I need to do is use JavaScript to alter the class when an option that isn't the currently selected on is clicked. I should say that I have the current class already setup in my CSS. I just have no way to trigger it.
I thought adding an onlick event to the <UL> up there and calling onclick="Javascript:changeCurrent();" but there is the problem (four actually):
Is <ul onclick="JavaScript:changeCurrent();> where I need to have the event?
What is the resulting JavaScript to make the change happen?
How can I cause the first option to be set as current by default?
Is there a way to keep the currently selected option from being an active link?
I found a few different examples but I couldn't tailor them to work for me. Any help would be most appreciated.

Since you specified that you wanted a non-jQuery response, here's a function that will toggle appropriately:
function toggleNavSelected(el){
var list = document.getElementById('nav').children[0];
for(var i=0; i<list.children.length; i++){
var cur = list.children[i];
if(el==cur){
cur.classList.add("current");
cur.firstChild.onclick = (function(){
toggleNavSelected(this.parentElement);
return false;
});
} else {
if(cur.classList.contains("current")){
cur.classList.remove("current");
}
cur.firstChild.onclick = (function(){
toggleNavSelected(this.parentElement);
});
}
}
}
Either add an onclick handler to each LI (onclick="toggleNavSelected(this);") or execute the following after the menu has loaded:
var list = document.getElementById('nav').children[0];
for(var i=0; i<list.children.length; i++){
var el = list.children[i];
el.firstChild.onclick = (function(){
toggleNavSelected(this.parentElement);
});
}
Demo: http://jsfiddle.net/bWY7P/2/
(note: The JSFiddle script has a small difference; it adds a return false; to the onclick function so that you can play with it without the links actually following the HREF attribute. Do not use that line in your live code)
Explanation:
The function looks at each LI element within the #nav element.
If that element is the element passed to the function, then it adds the class .current.
Otherwise, it removes the class .current (if present).
The second part binds a function to the onclick event of each a element that calls the toggleNavSelected() function and passes its parent element (the li) as the argument.

1) if you want to change the currently selected class when you click an item, put the onclick into the li item
2) using jquery would be very easy here, all you have to do is import the jquery file with the <script> tag and you're ready! For example, you could do onclick="changeClass(this);" on the <li> tag and in a normal JavaScript file or in a script tag:
function changeClass(this){
$('#nav li').attr("class","");
$(this).attr("class","current");
}
Replace the 'current' with the class name you want to use
3) it should already be set as current
4) use the :visited CSS selector to change what colour followed links look like eg:
a:visited{
color: #000000;
}

First of all you should set the event handler from a separate script, not from an onclick attribute. You don't repeat your code that way and have anything in one place. The HTML is also much cleaner.
Using jQuery it would be as easy as:
var menuLinks = jQuery( '#nav a' );
menuLinks.on( 'click' function() {
menuLinks.removeClass( 'active' );
$( this ).addClass( 'active' );
} );
You could also do that in plain JS, but using some library keeps you out of the trouble of browser incompatibilities.

Related

Newbie addEventListener style CSS change all <li>

This is so basic. I'm trying to model various addEventListener scenarios to simply change css style elements.
Here is the html
<ul>
<li>bullet 1</li>
<li>bullet 2</li>
</ul>
here is the javascript
const giraffe = document.querySelector("li");
giraffe.addEventListener("click", myFunc);
function myFunc(){
giraffe.style.backgroundColor = "#f00";
}
I'm trying to understand the behavior.
Why does this only work when you click on the first li (nothing happens when you click the second)
Why don't all the lis change color when you click on one li
Total newbie. I just about understand arrow functions and can read anonymous functions but I find it easier to follow if you can spell out any extra functions
This is because that the query selector only selects the first occurence that fits the criteria. Consider adding IDs on the HTML elements and select them accordingly.
Although you have more than one of the similar elements, querySelector is only applied to the first element always. It's also the reason why your style only works on giraffe which is the first element.
If you want your click event and style to be applied to all similar elements, you should use querySelectorAll and a loop forEach to change element by element.
const giraffes = document.querySelectorAll("li");
giraffes.forEach(giraffe => giraffe.addEventListener("click", myFunc));
function myFunc(){
giraffes.forEach(giraffe => giraffe.style.backgroundColor = "#f00");
}
<ul>
<li>bullet 1</li>
<li>bullet 2</li>
</ul>
It works on only the first one because that is the behavior of document.querySelector it returns the first element within the document that matches the specified selector, or group of selectors. If you want it to affect all the li elements you should consider using document.querySelectorAll
That's because the click event is attached to just the first li element and this code: giraffe.style.backgroundColor = "#f00"; is changing the background color of just that element.
You can improve your code using the below snippet.
const lis = document.querySelectorAll('li');
lis.forEach(li => {
li.addEventListener('click', () => {
li.style.backgroundColor = "#f00";
})
});

Get the first <ul> element from the post body

I want to use Javascript or jQuery to get the first <ul> element the post body and display it. On Blogger, the tag <data:post.body/> displays the whole post.
<div class="post-cover">
<img src="BIG-IMAGE"/>
</div>
<ul>
<li>CONTENT 1</li>
<li>CONTENT 2</li>
<li>CONTENT 3</li>
<li>CONTENT 4</li>
</ul>
The reason is: I need these ul elements to display in the homepage, but I cannot load the original image because they are all large and would affect the loading time dramatically.
I also cannot use display: none for the image because it loads the same way. I'm using Blogger.
I think it is similar when getting a thumbnail (first src) or the first string (for summaries) but I don't know how to make it.
UPDATE
ul:first gets the first ul element on the page.
$("ul:first").css(//whatever you want to do);
You can use $("ul:first") to get the ul and use any jquery function to work with that element.
to get the first element of a div
In your case, that's an img but not a ul tag.
If you really want to get the first element whatever it is, you can do it this way:
$(".post-cover").children().first().css({ // ... });
jQuery children() takes all children in DOM
jQuery first() takes the first one of them
However, if you know which element you are going to take, it is better to give him a name and access it using a name:
// HTML
<div class="post-cover">
<img src="BIG-IMAGE" id="post-cover-image"/>
</div>
// JS
$("#post-cover-image").css({ // ... });
As the post title says - get the first element from a div (and display it, using jQuery):
$( ".post-cover ul" ).first().show();
Preload images, which it seems you may be trying to actually do:
$.preloadImages = function() {
for (var i = 0; i < arguments.length; i++) {
$("<img />").attr("src", arguments[i]);
}
}
$.preloadImages("BIG-IMAGE.jpg");
First you need to find the image element of the div which like this :
var div_post_cover = document.getElementsByClassName("post-cover")[0];
Note : [0] is for the first DIV that have a class of post-cover
Then you need to get the first element inside the DIV and code was like this :
var img_first = div_post_cover.children[0];
or
var img_first = div_post_cover.getElementsByTagName("img")[0];
Then you will get the value of the src
var img_first_src = img_first.src;
This will be the summarized code.
var img_src = document.getElementsByClassName("post-cover")[0].children[0].src;
You need to try this if works.
<script type="text/javascript">
window.onload = (function(){
//document.getElementsByClassName("post-cover")[0].children[0].src
alert(document.getElementsByClassName("post-cover")[0].children[0].src);
});
</script>
You can use show() and hide() :
$( ".post-cover ul:first" ).hide();
$( ".post-cover ul:first" ).show();

Active link after click [duplicate]

This question already has an answer here:
Add ".active" class to the current page's link in a menu using jQuery or PHP [closed]
(1 answer)
Closed 8 years ago.
I cant find a way to add a class to an "a" element of a nav bar.
This is the html nav and the jQuery (applied to test.html url only, to test it):
$(document).ready(function() {
$("a").click(function() {
var actRef = $(this).attr("href");
if (actRef === "test.html") {
$("a[href='test.html']").addClass("active");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<nav>
<ul>
<li>Inicio
</li>
<li>Test
</li>
<li>Item
</li>
<li> test2
</li>
</ul>
</nav>
This isnt working, it just doesnt do anything, but if i change the .click to .hover it works fine adding the class but doesnt go to the link so the info of the page wont change.
I also tried this: How to change active class while click to another link in bootstrap use jquery? but neither works because of the e.preventDefault();...
If i take out the preventDefault it wont add the class but it will forward to the link...
PD: The aim is to let the user know on which tab he is actually on depending on the menu link he clicked.
Why not use then anchors :active state:
a:active {
/* your .active styles */
}
You code is not working as you are trying to set class on some link using javascript, and then navigating same time. So thing is the part where you are changing class for link is working actually, however you are not able to see it as after navigation html will be reloaded.
To solve this problem , you need write a common function for updating the class of link, in your common html. However, call that function from the html being loaded at onload event instead of calling at click.
Your common js or html will be having function :-
highlightlink(linkid){
$("a[href=' + linkid +']").addClass("active");
}
Each html will call this functin onload with respective htmlname.
For example test.html will hat this code :-
$(document).ready( function (){
highlightlink('test.html')
});
});
While index.html will have :-
$(document).ready( function (){
highlightlink('index.html')
});
});
Once your html is loaded, the that particular html will loaded
Do you really need to add a class to the html element? If it's about styling I think it might be possible to solve your styling using a simple :active pseudo selector. See example below:
li:active {
background-color: #f99;
}
li a:active {
color: #fff;
}
<nav>
<ul>
<li>Inicio
</li>
<li>Test
</li>
<li>Item
</li>
<li> test2
</li>
</ul>
</nav>
So what you can do is you can add a page link in the URL querystring like:
www.example.com/test.html?pageinfo=test.html
Now after the successful page loads you can retrieve page info from the query string and then you can add an active class to the anchor tag.
This way you will get querystring like this pageinfo=test.html and after successful parsing of querystring you will convert the information to {pageinfo:test.html}.
Using that you can add style/class to the anchor tag.
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");
});

Remove class from element and add to next element

I have a list of links, one has the class active.
On my next button click id like to remove the class from the current element and add it to the next only I cant seem to get it to add?
Ive made a fiddle to hopefully explain my problem, any help would be great, thanks
http://jsfiddle.net/h6D4k/
$('.next').click(function(){
$('ul.pagination').find('a.active').removeClass('active');
$('ul.pagination').find('a.active').next('a').addClass('active');
return false;
});
One of the jQuery most usable conveniencies is that its methods are (usually) chainable - in other words, they return the very object they are called from. So you can simply write this:
$('ul.pagination').find('a.active').removeClass('active').closest('li')
.next('li').find('a').addClass('active');
... as it's <li> elements that should be 'nexted', not <a> ones. But in fact, you shouldn't probably discard 'active' altogether if it's the last element in question:
var $a = $('ul.pagination').find('a.active'),
$li = $a.closest('li'),
$nextLi = $li.next('li');
if ($nextLi.length) {
$a.removeClass('active');
$nextLi.find('a').addClass('active');
}
This is actually what you want based on your html structure in you fiddle. http://jsfiddle.net/h6D4k/1/
$('ul.pagination').find('a.active').removeClass('active').parent()
.next().find('a').addClass('active');
Because once you've done this...
$('ul.pagination').find('a.active').removeClass('active');
There is no more a.active - the active classname has been removed from that element. So repeating the same selector...
$('ul.pagination').find('a.active')//...
... will select nothing.
Chain it all together instead.
$('ul.pagination').find('a.active').removeClass('active').next('a').addClass('active');
You have a second problem. According to the jQuery API for next(), it will:
Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
You're not trying to get the following sibling:
<ul class="pagination">
<li><a class="one active" href="#">X</a></li>
<li><a class="two" href="#">X</a></li>
<li><a class="three" href="#">X</a></li>
</ul>
Next
Prev
You're trying to get the next <a> in the whole document. That's more challenging - and I'm not sure how to do it.
I would write it this way, preventing the action from doing anything on the last li as well.
http://jsfiddle.net/h6D4k/6/
$('.next').click(function(e){
e.preventDefault();
if ($("ul.pagination a.active").parent().is(":last-child")) return;
$('ul.pagination a.active').removeClass('active').parent().next().find("a").addClass('active');
});
You have two errors in your code:
Once removed, the active class can't be found anymore
your a tags are nested in li tags so next() doesn't work as you expect
To simplify things, you could attach the active class to the li tags.
Live demo: http://jsfiddle.net/h6D4k/7/
Code:
$('.next').click(function(){
$('ul.pagination').find('li.active').removeClass('active')
.next().addClass('active');
return false;
});

javascript driven navigation menu on footer

My navigation menu on header looks like this:
<ul id="nav">
<li id="home">
<a class="mainmenu" href="#">Link1</a>
</li>
<li>
<a class="mainmenu" href="#">Link2</a>
</li>
</ul>
and the same markup is used for the footer section and it's not working.
I have also a file called jscript.js which contains all the javascript for the website,
and I found this variable:
var navTarget = "ul#nav li a" //menu link to target
Also, if I remove for example the markup in the header sections the footer will work.
I've tried also to use .nav instead of #nav and I have the same problem.
The navigation menu is controlled by javascript, I don't post the code here because it's huge, for better understanding of how the navigation menu works look here
I've found this in the javascript:
//SET MENU ITEM IDs
$(navTarget).each(function(i){
i++
this.id = this.id +"_" +i ;
});
//MENU CLICK FUNCTION
$(navTarget).click(function() {
//ensure link isnt clickable when active
if ($(this).hasClass('active')) return false;
//get id of clicked item
activeNavItem = $(this).attr('id');
//call the page switch function
switchContent();
});
//CONTENT SWTICH FUNCTION
var switchContent = function (){
//set previous and next link & page ids
var PrevLink = $(navTarget+'.active')
$(PrevLink).removeClass('active');
var PrevId = $(PrevLink).attr('id');
//alert(PrevId)
var NextLink = $('#'+activeNavItem).addClass('active');
var NextId = activeNavItem
//alert(NextId);
From the looks of it, the JS code is using some CSS selector (like jquery's $ or dojo's dojo.query) that pulls in the DOM element target based on the value of navTarget, and then does something with it: turns it into a menu.
But its only doing it once.
You need to look at the JS and see where navTarget is used. Then it should be fairly easy to make it do the menu creation on all the results of $(navTarget) instead of just the first hit.
Also, you should only have on instance of an ID in your dom.
You can change this to a class instead:
var navTarget = "ul.nav li a"
And in the markup:
<div class='nav'>
But you will still have to look at the JS and make sure it functions against a set of targets returned by the CSS selector. That code is probably expecting just a single result and using just it: results[0].
You can only have one element of a given id on the page. So based on your description, it sounds like you have 2.
I don't know exactly how this script works, but you can try using classes instead.
<ul class="nav">
var navTarget = "ul.nav li a";
You would have to change your HTML and the JS navTarget selector string.
But there is also a good chance that your script may not support creating multiple menus at all. And if thats the case, you may need to fix that script or find a better one.
If the code for the footer really is identical to the header, that's the problem. An id should only be used for a single element in a page, and jQuery's selectors will only return the first. Meaning code like "ul#nav li a" only works on the header.
Easiest solution is to change the id's to classes, e.g.:
<ul class="nav">
... and change your jQuery to match that, e.g.:
var navTarget = "ul.nav li a";
Update: And (ignoring that this may end up turning into three duplicate posts), that fix is probably not enough at all, since other parts of the script may only work with a single menu.

Categories

Resources