remembering the class of an element for later - javascript

I have a series of link on my pages with random a:hover classes so they display different colors on mouse over.
When a link is clicked its set to a different class so that it looks highlighted or active.
I need to create a script that first saves the class of the clicked link and then after it is changed and a new link is clicked finds the highlighted element and changes it back to the original class it was before changing the new active link.
What is the best way to store the class of the link until the new link is called.
Something like:
Get the class of the previous highlighted link from a variable?
Set the previous link to its original class.
Store the current class of the new link.
Set the element as the current highlighted link.

var old_link = null;
function store(ele){
old_link = {
cn: ele.className,
r: ele
}
}
function restore(){
old_link.r.className = old_link.cn;
}

I'd do this slightly differently.
For any links that you want included, they should all have the same class, let's say 'link-class'.
When you click on a particular link you'll want to add the class of 'selected' to that link, but first you'll want to remove the 'selected' class from all links on the page with the class of 'link-class'.
In jquery it would look like
$('a.link-class').click(function() {
$('a.link-class').removeClass('selected');
$(this).addClass('selected');
});

Related

How to access sub-elements in current object within JavaScript/jQuery?

Above I have three banner elements that I want to mark as unread if they are clicked. I structured each banner so that they have a span element within a nested div as shown with the image below (the red dot comes from the span element):
My javascript for this function is the following code:
I am trying to add a class ".read-dot" to the ".dot" span element that will hide it. I would like to add this class to the ".dot" span element that is inside the div that the user would click on. Any help would be appreciated.
I tried accessing the this.$(".dot) to access the dot element of the current object that triggered the event, but I now see this syntax is incorrect. I am new to jQuery which is why I tried this; I also could not find the page most relevant to my question on the API doc.
First, you have to remove click accessibility for the child.
$('div.banner > *').css('pointer-events', 'none');
And then, you can use the jquery selector for the .unread class to remove the class and replace .dot with .read-dot
$('.unread').click((e) => {
let clickedElm = e.target;
clickedElm.classList.remove('unread');
clickedElm.querySelector('span').classList.remove('dot');
clickedElm.querySelector('span').classList.add('read-dot');
})

Add class to a div after page direct to another page

It's little complicated for me (even to explain) but I try.
I have a footer with couple of specific links which should:
direct users to another page
and then to specific tab by adding a class "active".
That another page has tabs which works with "active" classes. So if user clicks one of the tab it becomes active (as it gets class "active"). Now I somehow need a solution so if user clicks on a link in footer (no matter the page) it directs to that page and also makes that certain tab active.
E.g I have tabs "Wood", "Stone", "Sand" which all gets the same "active" class after it has been clicked. Now I have a footer with same links "Wood", "Stone", "Sand". And if user clicks on one of the links in footer (no matter the page) it should be directed to that specific tab.
Basically I can direct user to those tab section as it has id (link-url#id) but can't figure out how to also add class so it becomes active.
I thought this could be done with js or jquery but as I searched for solution it seems it's not possible. I can also use PHP (if it's server side related) but not sure how.
EDIT:
Thanks for guidance! I managed to create one solution. Not sure if it's the best but it works as needed.
direct users to another page - just add regular url with id to a link. E.g "mypage.com/pagename#wood
And then to specific tab by adding a class "active" - code below
jQuery(document).ready(function( $ ){
// if url includes my page name with id
if (window.location.href.indexOf("pagename#wood") > -1) {
// add class active to div which has id of wood and remove active class from other siblings
$('#wood').addClass("active").siblings().removeClass('active');
// add class active to tab content div which has id of wood-content and remove active class from other siblings
$('#wood-content').addClass("content-active").siblings().removeClass('content-active');
}});
This is NOT possible with classes, because the class in HTML is an attribute that can be same for many tags, and if it works with the class the browser confuse which class you call, so it is a general rule that every browser follow it.
It is possible only with ID, as you said.
you can see this link for different between ID and CLASS.
For a single web application you can create a function that will triggered every load of the page, something like
function handlerTag () {
const url = new URL(document.baseURI)
const hash = url.hash.replace('#', '')
// add your logic for the 'active' class
}
url API
**you can change as per your logic. or you might have #Key with url find it and add class **
$(document).ready(function () {
$(function () {
debugger;
$('.side-navbar a').each(function () {
var currenturl = $(this).attr("href");
if (currenturl.indexOf('?') > 0) {
currenturl = currenturl.split('?')[0];
}
if (currenturl == window.location.pathname) {
$(this).parent().addClass("active");
}
});
}); });
HTML
<nav class="side-navbar box-scroll sidebar-scroll">
<ul class="list-unstyled">
<li>
Dashboard
</li>
</nav>
direct users to another page - just add regular url with id as a link. E.g "mypage.com/pagename#wood
And then to specific tab by adding a class "active" - code below
jQuery(document).ready(function( $ ){
// if url includes my page name with id
if (window.location.href.indexOf("pagename#wood") > -1) {
// add class active to div which has id of wood and remove active class from other siblings
$('#wood').addClass("active").siblings().removeClass('active');
// add class active to tab content div which has id of wood-content and remove active class from other siblings
$('#wood-content').addClass("content-active").siblings().removeClass('content-active');
}});

Add overlay on specific images selected (no more than 3)

I have a grid of cards, right now clicking one of the cards adds an overlay to all of them.
I need:
1.- If user clicks one cards, and only that card gets the overlay.
2.- No more than 3 cards at a time can have an overlay. User would have to click one of the already clicked cards to diselect it, in order to select another one.
Codepen:
https://codepen.io/ogonzales/pen/yLJGzYr
JS Code:
$('.imageDiv').click(function(){
$('img').toggleClass("tricky_image");
$(".text").toggleClass("display-inline");
});
Expected result:
Try this instead. Make use of this so that the relevant scope is preserved.
$('.imageDiv').click(function(){
$(this).find('img').toggleClass("tricky_image");
/*$(".text").css("display", "inline");*/
$(this).find(".text").toggleClass("display-inline");
});
You could equally (maybe) use the .children() method (as opposed to .find()) but I didn't know exactly how your dom structure was inside each "imageDiv".
Your specified click function search for every 'img' element and every node with a .text class.
What you actually want, is to get the child img element and .text of the clicked .imageDiv
By limiting the queried scope with $(this).find(...) we only search for child elements of the clicked .imageDiv.
With some additional logic your second requirement can be also fulfilled ->
$('.imageDiv').click(function(){
const trickyCount = $(".tricky_image").length;
const img = $(this).find('img');
const text = $(this).find(".text");
if(trickyCount < 3 || img.hasClass("tricky_image")){
img.toggleClass("tricky_image");
text.toggleClass("display-inline");
}
});

Add class to anchor-link on other page

I've got a navigation set up with links to anchors on specific page.
This works when on that specific page, but how can I add the class when coming from another page on my site?
<script>
jQuery(function ($) {
$( document ).ready(function() {
$(".sub-menu > li > a").on("click", function(){
$("a.active").removeClass("curlink");
$(this).addClass("curlink");
});
});
});
</script>
Simply pass one more hidden input element say with id navigator
when you are clicking on a link with id #a1 then set this hidden element value to "a1"
Send this element with form
On receiver page check for value of this element say $("#navigator").val();
On the basis of the value of this, which is "a1" in this case, set CSS of link with id a1 whatever you want, using $("#a1").css();
Another method is that on every hyperlink add a GET parameter and receive on the receiver side and on the basis of its value set CSS.
Let's say there are 3 links with id a1,a2,a3
Add a parameter say cameFrom in href URL e.g. href=".../*.html?cameFrom=a1" for link a1 and href=".../*.html?cameFrom=a2" for link a2 and so on
On receiver page get its value by using this function:
function param(name){
return (location.search.split(name + '=')[1] || '').split('&')[0];
}
Use param(cameFrom) and get result.
Link to this function
There are many ideas/ways to achieve this, but if you have separate file which contains navigation code then you can do one way,
you can put in a hidden element with value of id of the <a> tag of menu of navigation. So when you land on the page and found that id value from the hidden field in jquery, you can make that <a> of navigation activated. I mean you can apply active class to that menu.
Tell me if this is not clear, I would try to make it simple.
In simple words,
Add one hidden element in your separate pages like <input type="hidden" value="about_us" id="nav-menu">
And in your master page,put jquery to get this value like:
var nav_menu = $('#nav-menu').val(); so in nav_menu you will have about_us as its value.
Now, in main master view file, you can write jquery to add active class for relevant manu like: $('.sub-menu > li > a').removeClass('active');$('#'+nav_menu).addClass('active');

How to change button class in a div while just the last one can keep the change?

I'm using this code to change my buttons's class:
$('button').on('click', function(){
var btn=$(this);
if(btn.attr('class')=='tct-button'){
btn.removeClass('tct-button').addClass('tct-button2');
}
else{
btn.removeClass('tct-button2').addClass('tct-button');
}
});
The problem is that I have multiple div's with multiple buttons in each. I need to change this so that every time I click on a button in a div the others which were changed by a previous click (in that same div) change back to the default class which is 'tct-button', and just the last clicked button turns to 'tct-button2'. Would you please help me.
use toggleClass in jquery ,there is no need to check hasClass()
$(this).toggleClass("tct-button2 tct-button");
DEMO
Use hasClass()
Determine whether any of the matched elements are assigned the given class.
Code
$('button').on('click', function(){
var btn=$(this);
if(btn.hasClass('tct-button')){
btn.removeClass('tct-button').addClass('tct-button2');
}
else{
btn.removeClass('tct-button2').addClass('tct-button');
}
});
However I think you need
$('button').on('click', function(){
$('.tct-button2').removeClass('tct-button2'); //Remove all class
$(this).addClass('tct-button2'); //Add the class to current element
});
If you want to add an additional class to your buttons (tct-button2) whilst keeping tct-button on every button you could do what Satpal suggested.
However, from the sounds of it and I may be wrong, if you want to change the classes so that each button only has one class at a time on it (either tct-button or tct-button2) you can do similar to what Satpal suggested and use:
$('button').on('click', function(){
$('.tct-button2').addClass('tct-button').removeClass('tct-button2'); //Add original class and Remove tct-button2 class
$(this).removeClass('tct-button').addClass('tct-button2'); //Add the class to current element
});
Here is the example http://jsfiddle.net/lee_gladding/xao46uzs/
to only affect buttons in the div the clicked one belongs to, use a similar method to:
$('button').on('click', function(){
$(this).parent('div').find('.tct-button2').addClass('tct-button').removeClass('tct-button2'); //Remove all class in that div
$(this).removeClass('tct-button').addClass('tct-button2'); //Add the class to current element
});
(You might want to use a better selector for the parent, possibly a class or what ever your actual html uses)
Example:
http://jsfiddle.net/lee_gladding/xao46uzs/3/

Categories