jQuery to add a class to menu items? - javascript

I have the following menu items:
<ul>
<li class="static">
<a class="static menu-item" href="/mySites/AboutUs">About Us</a>
</li>
<li class="static">
<a class="static-menu-item" href="/mySite/Practices">Practices</a>
</li>
<li class="static">
<a class="static-meunu-item" href="/mySite/Sectors">Sectors</a>
</li>
</ul>
I cannot add specific background images to the menu items as they all have the same class. In order to achieve this it will be ideal if specific classes could be added for example:
<ul>
<li class="static">
<a class="static menu-item about-us" href="/mySites/AboutUs">About Us</a>
</li>
<li class="static">
<a class="static-menu-item practices" href="/mySite/Practices">Practices</a>
</li>
<li class="static">
<a class="static-meunu-item sectors" href="/mySite/Sectors">Sectors</a>
</li>
</ul>
In the above example highlighted in red are the classes that have been added. This will then allow me to add the specific background images to each menu item.
How can I achieve this using the .addClass() method in jQuery?

In this case, adding specific classes is overkill. I would simply use an href selector since that seems to be what you're basing your classes off of:
// *= indicates contains
$('a[href*="AboutUs"]').addClass("about-us");
$('a[href*="Practices"]').addClass("practices");
$('a[href*="Sectors"]').addClass("sectors");
If there are other anchors on the page with the same href's that you don't want to include, simply use the parent > child selector:
// *= indicates contains
$('.static > a[href*="AboutUs"]').addClass("about-us");
$('.static > a[href*="Practices"]').addClass("practices");
$('.static > a[href*="Sectors"]').addClass("sectors");
Here is a working jsFiddle to illustrate the solution.

You should be able to add a class by passing a callback function to the addClass function -
$("a").addClass(function() {
var newclassname = $(this).text().toLowerCase();
return newclassname.replace(/ /g,'-');
})
Demo - http://jsfiddle.net/aZEZN/

I personally find it overkill to do such things with Javascript.
Makes more sense doing it server side as it's been mentioned above.
Or...
CSS! You could use CSS3 pseudo classes to do this.
I have created an example here
To make this work in older browsers such as IE7, make sure you add Selectivizr to your head section

define your class like this;
.highlight { background:yellow; }
.highlight2 { background:yellow; }
.highlight3 { background:yellow; }
then add your class like this;
$(".about-us").addClass("highlight");
$(".practices").addClass("highlight2");
$(".sector").addClass("highlight3");

It's not necessarily overkill specifying individual classes for each list item. A class should be used (as opposed to an ID) when there is even a possibility to group multiple elements together (for scripting, styling). In your case, as this is a navigation menu, you might have multiple menus (such as a left-side pane side bar, a footer menu aswell). From my experience, I would specify each menu button as its own class in order to handle the group of links together (ie all links that directs the user to the About us page).
The most obvious benefit of this is that you will be able to handle the active links as a group vs. individually; just as you would have a hover color on these links, you might as well want the link to be bold when the user is on that specific page. Grouping the links together and handling this as a class would allow you to bold all the links if you have multiple menus.
To add to this, erimerturk had a good idea of specifying highlights or 'themes' within your styles. This is a good practice (although not for your case) when you want to specify a certain color scheme for your site. Specify your color, background color and highlights as classes and tag these classes to the required elements within your html directly. This is a huge boost for maintainability and scalability, so although I wouldn't say as far as saying it's good practice, it's certainly not bad practice as far as I'm concerned.

Overkill or not, sometimes we may just want to test out ideas quickly on the browser, or you might be working on nodejs. I have edited the link classes to static-menu-item.
var links = $("body").find("a.static-menu-item");
$.each(links, function(value) {
var items = $(this).attr('href').split("/");
$(this).addClass(items[items.length-1].toLowerCase() );
});
Working example

Related

Ideal selector for Cypress automation Javascript

I have this HTML code
<li class="menu-level-1">
<a href="/Public/app/#/calendar">
<i class="site-menu-icon material-icons">date_range</i>
<span>
Calendar
</span>
</a>
</li>
I don't know exactly what I need to select in CYPRESS for automation to press the calendar button. I don't have a unique css or id class so I can't isolate it from the rest of the menu items. I only have what is seen in this code.
I think you want to click the element <a href="/Public/app/#/calendar"> since it has the href.
There's lots of ways to target it, the one to use depends on what is unique on the page
cy.contains('a', 'Calendar').click() // if the word Calendar only appears on this link
cy.get('a[href="/Public/app/#/calendar"]').click() // specifies by the link itself
cy,get('i.site-menu-icon').parent().click() // if the icon is the unique thing
You can use custom xpath like //*[text()="Calendar"]
If you have found many others on your web page, you can give an index like //*[text()="Calendar"][1] make sure here the index always starts with 1, not 0.

Not able to open sub menus in html

I am working on a HTML website. In Website menus are working properly on desktop screen. But In mobile version Parent menus are opening properly as a dropdown. but when I trying to open sub menus it is not opening. If I click on icon , it is redirecting to a page which is linked to parent menu.
I just want to open sub menu dropdown when I click on a icon. But Parent menu link should be there.
I am very new to javascript. Please help me to solve my problem.
Here is my html code
<nav class="navigation">
<ul>
<li> HOME
</li>
<li> <span>WHO WE ARE </span>
<i class="ion-ios-plus-empty visible-xs"></i>
<ul class="sub-nav">
<li>
Vision
</li>
</ul>
</li>
</ul>
</nav>
and hrere is my js
$('.sub-menu >a').on('click', function() {
if ($(window).width() <= 767) {
$('.sub-menu').removeClass('on');
$('.sub-menu> ul').slideUp('normal');
if ($(this).next().next('ul').is(':hidden') == true) {
$(this).parent('li').addClass('on');
$(this).next().next('ul').slideDown('normal');
}
}
});
please help
Your code is very messy, so first I'll answer the question generally: If you want an event to occur when clicking a link without the link actually opening, you must stop the event from firing. There are 3 ways to do that (I included a link in the bottom of my answer regarding which does what), here I chose e.preventDefault():
document.getElementById("myspeciallink").addEventListener("click", function(e) {
alert("A different action!");
e.preventDefault(); //return false / stopPropagation could've also worked here
});
I'm a link!
Regarding your code:
You're trying to bind an event to sub-menu, which doesn't exist in your code.
The sub-menu > a selector only applies to direct children, so for your selector and the following example code only example B would apply to the selector. Perhaps sub-menu a would be better suited here:
$(".sub-menu > a").click(() => alert("Clicked"))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="sub-menu">
<li>
Example A
</li>
</ul>
<br/>
<ul class="sub-menu">
Example B (Which is what you did but not what you want)
</ul>
Animations based on screen size (a.k.a Responsive Web Design) shouldn't be done like this unless you don't have a choice, and you do. It is preferred you use CSS to achieve what you're trying to accomplish with transistions. I recommend reading more on this subject.
I highly recommend learning CSS, JS and HTML better in order to have a better understanding of what's going on and of good & bad practices.
See also:
What's the difference between event.stopPropagation and event.preventDefault?
Couple of things here.
First of all you apply jQuery code for element $('.sub-menu >a') which means that it will applay to all a elements which are direct children of .sub-menu element.
But you don't have element wih class .sub-menu. You should add it to direct parent of an a element to which it should be applied.
Secondly, if you don't want the a tag to redirect you, then you shiuld add event.preventDeault() where event is an event variable which you can get in .on() function like this $('.sub-menu >a').on('click', function(event) {...
Lastly, this code
$('.sub-menu').removeClass('on');
$('.sub-menu> ul').slideUp('normal');
if ($(this).next().next('ul').is(':hidden') == true) {
$(this).parent('li').addClass('on');
$(this).next().next('ul').slideDown('normal');
}
works that way that firstly it hides all dropdowns and then opens teh one you clicked. If it is desired behavior, then ignore this. But I don't think it is.
Why? Because right now when you click on visible dropdown a tag (the one that opens it) you would expect the dropdown to hide. And in your case it will hide and show again. But if you want it to work that way, then no problem. The code is correct.

Navigate to specific anochor tag via up and down arrow press

I am currently using anchor tags and have implemented smooth scrolling on 5 links. This currently works perfectly. However, I would now like to add the ability to use the arrow keys to navigate through these same anchor tags.
I can only fumble through javascript and jquery, so I'm pretty confused when it comes to that stuff.
<ul>
<li class="scrolldot"><span>1</span></li>
<li class="scrolldot"><span>2</span></li>
<li class="scrolldot"><span>3</span></li>
<li class="scrolldot"><span>4</span></li>
<li class="scrolldot"><span>5</span></li>
<li class="scrolldot"><span>6</span></li>
</ul>
So basically, I want a user to hit the down arrow and them to be taken to the next section, depending on where they are on the page. If they are on section 2, take them to three. If they hit up again, they would be taken back to two and so forth. Make sense?
Checkout Mousetrap. It's a nifty little library that makes binding keys pretty easy. There are a few good examples on the site as well.
Perhaps something like this would suffice:
Mousetrap.bind('up', function() {
your_up_function();
});
Mousetrap.bind('down', function() {
your_down_function();
});

Hide anchors using jQuery

I've created a dynamic page that, depending on the view type, will sometimes utilize the anchor tags and other times not. Essentially, I want to be able to control if on click the page jumps to the anchor. Is it possible to hide anchor tags using jQUery, so they are essentially removed? I need to be able to re-enable the anchors when necessary, and always show the current anchor in the browser's address bar. It seems to work in FireFox, but not in Internet Explorer.
I have three sections: the 'table of contents', the content, and the javascript (jQuery) code
Table of Contents
<a id="expandLink0" class="expandLinksList" href="#green">What is green purchasing</a><br>
<a id="expandLink1" class="expandLinksList" href="#before">Before you buy</a><br>
Contents
<ul id="makeIntoSlideshowUL">'
<li id="slideNumber0" class="slideShowSlide">
<a name="green"></a>
<div>Green Purchasing refers to the procurement of products and service...Back to Top</div>
</li>
<li id="slideNumber1" class="slideShowSlide">
<a name="before"></a>
<div>We easily accomplish the first four bullet points under...Back to Top</div>
</li>
</ul>
jQuery On Page Load
$(".slideShowSlide").each(function() {
$(this).children(":first-child").hide();
});
jQuery to re-enable links
$(".slideShowSlide").each(function() {
$(this).children(":first-child").show();
});
I've also tried prepending an extra character to all anchor names to 'disable' them, but IE won't change the names using attr("name"). The only real manipulation it's letting me do is remove().
Try doing it this way:
$(".slideShowSlide").each(function() {
$(this).children().first().hide();
});
Or even this way:
$(".slideShowSlide").each(function() {
$(this).children(':first').hide();
});

Need help creating dynamic Javascript Arrays

Part One:
I'm trying to figure out how to use the DOM and Javascript to create an array containing the links in multiple lists.
The problem is I need each UL to have a unique array containing the links; the only unique ID I am able
to use in this case is the name value in the link tags. I will not be able to add anything else to the markup.
The javascript reference will need to be contained in a single script, with one reference to the script at the
bottom of the page.
Part Two:
What I ultimately need to do, is to hide each of the lists, and replace them with just the first two links,
along with a "view all" link below the two links that, when clicked, adds the other two links to the list.
Again, I can't add any markup, divs, etc. etc.; it must be completely based on the information below, the DOM and
javascript.
Thanks for any help y'all can provide!
<ul>
<li>
Section One, Article One
</li>
<li>
Section One, Article Two
</li>
<li>
Section One, Article Three
</li>
<li>
Section One, Article Four
</li>
</ul>
<ul>
<li>
Section Two, Article One
</li>
<li>
Section Two, Article Two
</li>
<li>
Section Two, Article Three
</li>
<li>
Section Two, Article Four
</li>
</ul>
I am using jQuery for my solutions ;)
Part One:
var list = new Array();
$.each($('ul'), function(index, value) {
list.push(new Array());
$.each($(value).find('li a'), function(index2, value2){
list[list.length - 1].push(value2.href);
});
});
Part Two:
I really don't understand the requirements, but have a look at jQuery it really makes those takes easy.

Categories

Resources