remove class from current group - javascript

The easiest way to see the problem is checking the code here: http://www.studioimbrue.com/beta
What I need to do is once a thumbnail is clicked, to removed the "selected" class from all other thumbnails that are in this same or without removing them from the other galleries on the page. Right now, I have everything working except the class removal. Someone helped me in another question but wasn't quite specific enough (my javascript skills aren't all that great!) I'm using jQuery. Thanks for the help.
Well in that case, I'm not sure why this doesn't work properly:
$(document).ready(function(){
var activeOpacity = 1.0,
inactiveOpacity = 0.6,
fadeTime = 100,
clickedClass = "selected",
thumbs = ".thumbscontainer ul li img";
$(thumbs).fadeTo(1, inactiveOpacity);
$(thumbs).hover(
function(){
$(this).fadeTo(fadeTime, activeOpacity);
},
function(){
// Only fade out if the user hasn't clicked the thumb
if(!$(this).hasClass(clickedClass)) {
$(this).fadeTo(fadeTime, inactiveOpacity);
}
});
$(thumbs).click(function() {
// Remove selected class from any elements other than this
var previous = $(thumbs+'.'+clickedClass).eq();
var clicked = $(this);
if(clicked !== previous) {
previous.removeClass(clickedClass);
}
clicked.addClass(clickedClass).fadeTo(fadeTime, activeOpacity);
});
});

I see you're using jQuery (and have edited your question accordingly).
With jQuery, it's really easy to get a list of matching elements using CSS syntax:
var list = $('#parentId > .selected');
That gets a list of the direct children of the element with the ID "parentId" that have the class "selected". You can then do things with them, such as:
list.removeClass("selected");
Then add "selected" to the element you want to select.
Edit I think this should do it:
$(thumbs).click(function() {
// Remove selected class from any elements other than this
var clicked, previous;
clicked = $(this);
if (!clicked.hasClass(clickedClass)) {
previous = $(thumbs+'.'+clickedClass);
previous.removeClass(clickedClass).fadeTo(fadeTime, inactiveOpacity);
clicked.addClass(clickedClass).fadeTo(fadeTime, activeOpacity);
}
});
I'm assuming there that the "selected" class isn't necessary for the fade effect to look right.
Note how the above will completely ignore the click if the clicked element already has the class. If you don't want that, remove the hasClass check and add .not(clicked) to the end of the previous = $(thumbs+'.'+clickedClass) line, but I don't know what your fade in would do at that point if you've already done it once.
I'm not getting the hover stuff; I thought you wanted this to happen on click, not hover.

You should take a look at
jQuery.removeClass()
So the point would be to first iterate trough all the images and unset the classname and than set the class on the active one.

Use .closest('.jcarousel-clip') to get the parent div,
then find all the thumbnails and use .removeClass('selected').

Hi Andy it isn't clear your question, but I am going to try to help you.
I am trying to help, and my skills on javascript arent that good either, plus I am not sure if I undertood the question right, please, dont vote me down.
function focusme(){
document.getElementById("focusme").focus();
}
function changeToCurrent(obj){
var menucont = document.getElementById('menu');
var arrLink = menucont.getElementsByTagName('a');
for (var i = 0 ; i < arrLink.length; i++){
arrLink[i].className='';
}
obj.className = "current";
}
<div class="menu" id="menu" >
<a href='' id='focusme' onclick='changeToCurrent(this)'>link1</a>
<a href='' onclick='changeToCurrent(this)'>Once Only link2</a>
<a href='' onclick='changeToCurrent(this)'>link3</a>
<a href='' onclick='changeToCurrent(this)'>link4</a>
<a href='' onclick='changeToCurrent(this)'>link5</
link6
</div>
Hope it helps.

Related

Make div appear or disappear with javascript

I am attempting to make a few divs behave the way I want them to. Here is my relevant HTML:
<ul class="services">
<li class="business-formation" id="services-li-1">Business Formation</li>
<li class="domestic-relations" id="services-li-2">Domestic Relations</li>
<li class="estate-probate" id="services-li-3">Estate & Probate</li>
</ul>
<div class="business-formation-list" id="business-formation-list">
<ul>
<li>Items go here</li>
</ul>
</div>
<div class="domestic-relations-list" id="domestic-relations-list">
<ul>
<li>Items go here</li>
</ul>
</div>
<div class="estate-probate-list" id="estate-probate-list">
<ul>
<li>Items go here</i>
</ul>
</div>
I want the divs to appear and disappear when the corresponding li is clicked (they are links). Here is my Javascript:
document.getElementById('services-li-1').style.cursor = "pointer";
document.getElementById('services-li-2').style.cursor = "pointer";
document.getElementById('services-li-3').style.cursor = "pointer";
const div1 = document.querySelector('business-formation-list');
const div2 = document.querySelector('domestic-relations-list');
const div3 = document.querySelector('estate-probate-list');
const click2 = document.getElementById('services-li-2');
document.addEventListener('click', (event) => {
if (event.click2.className = 'domestic-relations') {
div1.style.display = 'none';
div2.style.display = 'block';
div3.style.display = 'none';
}
});
This doesn't make anything happen, but what I wanted it to do is to make the second div appear when the li with the class name "domestic-relations" is clicked. What am I doing wrong? Thanks!
If you're using querySelector, you need to tell it that it's a class. You do that by adding . before the class in question.
So document.querySelector('business-formation-list') should be document.querySelector('.business-formation-list').
However, if you're only using it once, it should be an ID, not a class.
Im also fairly new to this and had a similar problem to yours. I came up with a solution, so it might help you as well. The solution is quite long so I hope you can bear with me.
first thing is to change your your div class "domestic/estate/business" to just "list". When you're doing the css for it, you'll want to apply the same style to them. If you need more styling, you can always target the IDs or add another css class.
Once you've done that, apply to that list "display: none;". This will hide all your ul's at once.
The javascript looks something like this. i've added some description as to why I chose to do what I did.
var serviceType = document.querySelectorAll(".serviceType");
var serviceTypeArray = Array.prototype.slice.call(serviceType); // this will
//change your serviceType from a nodelist to an Array.
var serviceDescription = document.querySelectorAll(".list"); // to grab the
//list of descriptions and make it into an "array"
for ( i = 0 ; i < serviceTypeArray.length ; i++) {
var services = serviceTypeArray[i]; // I created this variable to store the
// variable "i"
services.addEventListener( "click" , displayServices); }
// created this "for loop" to loop through every element inside the array
//and give it the "click" function
function displayServices() {
var servicePosition = serviceTypeArray.indexOf(this); // when we click the
// event, "this" will grab the position of the clicked item in the array
if (serviceTypeArray[servicePosition].hasAttribute("id") == false) { //
// the hasAttribute returns values of true/false, since initially the
// serviceTypeArray didn't have the "id" , it returns as false
serviceTypeArray[servicePosition].setAttribute( "id" , "hide"); // I've
// added the "setAttribute" function as a unique indicator to allow
// javascript to easily hide and show based on what we are clicking
serviceDescription[servicePosition].style.display = "block"; // When you
//click one of the serviceType, it returns an the index number (aka the
// position it is inside the arrayList)
//this gets stored inside servicePosition(aka the actual number gets
// stored).
// Since i've made an array to store the the description of each service,
// their position in the array correspond with the service's position
//inside the serviceType array made earlier; therefore, when I press one
// particular serviceType (ie i clicked on "business formation"), the
// appropriate text will pop up because the position of both the name and
// its description are in the same position in both arrays made
} else if (serviceTypeArray[servicePosition].hasAttribute("id") == true ) {
//since the serviceType now has an attribute, when we check it, it'll come
// back as true
serviceTypeArray[servicePosition].removeAttribute("id"); //we want to
// remove the id so next time we click the name again, the first "if"
// condition is checked
serviceDescription[servicePosition].style.display = "none"; //this is
// so that the display goes back to "none"
}
}
This will allow to click any of the names and display/hide them at will. you can even show 2/3 or all three of them, it's up to you. I hope this helps and I hope the explanation is clear enough!
Let me know if you have any questions for this!

jQuery slideDown not working on element with dynamically assigned id

EDIT: I cleaned up the code a bit and narrowed down the problem.
So I'm working on a Wordpress site, and I'm trying to incorporate drop-downs into my menu on mobile, which means I have to use jQuery to assign classes and id's to my already existing elements. I have this code that already works on premade HTML, but fails on dynamically created id's.
Here is the code:
...
var menuCount = 0;
var contentCount = 0;
//find the mobile menu items
var submenus = $('[title="submenu"]');
if (submenus.length && submenus.parent('.fusion-mobile-nav-item')) {
console.log(submenus);
submenus.addClass('dropdown-title').append('<i id="dropdown-angle" class="fa fa-angle-down" aria-hidden="true"></i>');
submenus.each(function() {
$(this).attr("href", "#m" + menuCount++);
})
var content = submenus.parent().find('ul.sub-menu');
content.addClass('dropdown-content');
content.each(function() {
$(this).attr("id", "m" + contentCount++);
})
}
$(document).on('click', '.dropdown-title', function(e) {
var currentAttrValue = $(this).attr('href');
if ($(e.target).is('.d-active') || $(e.target).parent('.dropdown-title').is('.d-active')) {
$(this).removeClass('d-active');
$(currentAttrValue).slideUp(300).removeClass('d-open');
} else {
$('.dropdown-title').removeClass('d-active');
$('.dropdown-content').slideUp(300).removeClass('d-open');
$(this).addClass('d-active');
console.log($(currentAttrValue));
//THIS LINE FAILS
$(currentAttrValue).slideDown(300).addClass('d-open');
}
e.preventDefault();
});
I've registered the elements with the class dropdown-title using $(document).on(...) but I can't figure out what I need to do to register the elements with the custom ID's. I've tried putting the event callback inside the .each functions, I've tried making custom events to trigger, but none of them will get the 2nd to last line of code to trigger. There's no errors in the console, and when I console log the selector I get this:
[ul#m0.sub-menu.dropdown-content, context: document, selector: "#m0"]
0
:
ul#m0.sub-menu.dropdown-content
context
:
document
length
:
1
selector
:
"#m0"
proto
:
Object[0]
So jQuery knows the element is there, I just can't figure out how to register it...or maybe it's something I'm not thinking of, I don't know.
If you are creating your elements dynamically, you should be assigning the .on 'click' after creating those elements. Just declare the 'on click' callback code you posted after adding the ids and classes instead of when the page loads, so it gets attached to the elements with .dropdown-title class.
Check this jsFiddle: https://jsfiddle.net/6zayouxc/
EDIT: Your edited JS code works... There also might be some problem with your HTML or CSS, are you hiding your submenus? Make sure you are not making them transparent.
You're trying to call a function for a attribute, instead of the element. You probably want $(this).slideDown(300).addClass('d-active'); (also then you don't need $(this).addClass('d-active'); before)
Inside submenus.each loop add your callback listener.
As you are adding the class dropdown-title dynamically, it was not available at dom loading time, that is why event listener was not attached with those elemnts.
var menuCount = 0;
var contentCount = 0;
//find the mobile menu items
var submenus = $('[title="submenu"]');
if (submenus.length && submenus.parent('.fusion-mobile-nav-item')) {
console.log(submenus);
submenus.addClass('dropdown-title').append('<i id="dropdown-angle" class="fa fa-angle-down" aria-hidden="true"></i>');
submenus.each(function() {
$(this).attr("href", "#m" + menuCount++);
// add callback here
$(this).click( function(e) {
var currentAttrValue = $(this).attr('href');
if ($(e.target).is('.d-active') || $(e.target).parent('.dropdown-title').is('.d-active')) {
$(this).removeClass('d-active');
$(currentAttrValue).slideUp(300).removeClass('d-open');
} else {
$('.dropdown-title').removeClass('d-active');
$('.dropdown-content').slideUp(300).removeClass('d-open');
$(this).addClass('d-active');
console.log($(currentAttrValue));
$(currentAttrValue).slideDown(300).addClass('d-active');
}
e.preventDefault();
});
})
var content = submenus.parent().find('ul.sub-menu');
content.addClass('dropdown-content');
content.each(function() {
$(this).attr("id", "m" + contentCount++);
})
}
Turns out my problem is that jQuery is adding to both the mobile menu and the desktop menu, where the desktop menu is being loaded first when I search for that ID that's the one that jQuery finds. So it turns out I was completely wrong about my suspicions.

Show/Hide Content without reloading the page

I have three content boxes that i want to show and hide using controls.
The HTML is as follows:
<div id="leermat1">
Content here
<a class="pag-next">Next</a>
<a class="pag-prev">Previous</a>
</div>
<div id="leermat2">
Content here
<a class="pag-next">Next</a>
<a class="pag-prev">Previous</a>
</div>
<div id="leermat3">
Content here
<a class="pag-next">Next</a>
<a class="pag-prev">Previous</a>
</div>
I have the two anchors pag-next and pag-prev that will control which of the content divs should be visible at any given point:
I want to write jquery such as, when #leermat1 'pag-next' is clicked, it hides #leermat1 and shows #leermat2. Then when #leermat1 is hidden and #leermat2 shows, when '.pag-next' is clicked, it hides #leermat2, and shows #leermat3.
Also the 'pag-prev' should work the same way.
I started with the following but dont know where to go from here.
$(document).ready(function() {
$('.pag-next').on('click',function() {
$('#leermat1').addClass('hide');
$('#leermat2').addClass('show');
});
});
One more thing is that the '.pag-next' should stop functioning after it has shown #leermat3.
You need this
$('[class^=pag-]').click(function() {
var elem = $('[id^=leermat]').filter(":visible"); // take the visible element
var num = Number(elem[0].id.match(/\d+$/)[0]); // take the number from it
var step = $(this).is('.pag-next') ? 1 : -1; // ternary operator
$('#leermat'+ (num + step)).show(); // show next or back
elem.hide(); // hide the visible element
});
Looks like in your anchor tag you have not given it a class.
Next
You then go on in your JQuery code to add a click function to a class which does not exist.
$('.pag-next').on('click',function()
Try adding class="pag-next" to your anchor tag.
This is what worked for me through a little trial and error. Although I am not sure if this is the most efficient solution.
$('#leermat1 .pag-next').on('click',function(){
$('#leermat1').addClass('hide');
$('#leermat1').removeClass('show');
$('#leermat3').addClass('hide');
$('#leermat3').remove('show');
$('#leermat2').addClass('show');
});
$('#leermat2 .pag-next').on('click',function(){
$('#leermat1').removeClass('show');
$('#leermat2').addClass('hide');
$('#leermat2').removeClass('show');
$('#leermat3').addClass('show');
});
$('#leermat2 .pag-prev').on('click',function(){
$('#leermat2').addClass('hide');
$('#leermat2').removeClass('show');
$('#leermat1').addClass('show');
$('#leermat3').removeClass('show');
});
$('#leermat3 .pag-prev').on('click',function(){
$('#leermat3').addClass('hide');
$('#leermat2').addClass('show');
$('#leermat1').addClass('hide');
$('#leermat3').removeClass('show');
$('#leermat1').removeClass('show');
});

How to keep the selected menu active using jquery, when the user comes back to page?

I have a typical menu structure -
<Ul class="nav">
<li>Menu1</li>
<li>menu2</li>
-------
</ul>
When I click on certain menu, as per my jquery written on load of layout.html, it selects particular menu.
<script>
jQuery(function(){
jQuery('.nav>li>a').each(function(){
if(this.href.trim() == window.location)
$(this).addClass("selected");
});
</script>
But on that page if I click on certain link which takes me on some other page and then when I come back the menu item does not remain selected.
How can I modify my jquery to achieve this?
Thanks in advance !
As SJ-B is saying, HTML5 Web Storage is a good solution.
If you don't intend to click more than one or two pages away from the page with your list menu, you could add a query to the link that takes you away form the page e.g. the id of one of your list menus.
href="somepage.html could become something like this href="somepage.html?menu_id=menu5
When using window.history.back(), you could then fish the id out of the URL using window.location.search and use id to select the list menu.
You can use simple css code. Use active attribute like
a:active
{
//Some style
}
You can use below code to achieve this.
var lastele=siteurl.substring(siteurl.lastIndexOf("/")+1);
jQuery(".nav>li> a").each(function(){
var anchorhref=jQuery(this).attr("href");
var finalhref=anchorhref.substring(anchorhref.lastIndexOf("/")+1);
if(finalhref==lastele){
jQuery(this).addClass("selected");
}
});
I would do something like this :
<ul class="nav">
<li id="home">Home</li>
<li id="contact">Contact</li>
</ul>
Javascript :
// http://mywebsite.com#home
// location.hash === '#home'
jQuery('.nav ' + location.hash).addClass('selected');
Try to use Session Object of HTML5.
sessionStorage.varName = id of selected item.
on load just check if the sessionStorage.varName has value or undefined, if not then get the value
`var value = sessionStorage.varName;` and set it.
Well there could be many ways, on which is this which i like and always use:
It works when you path name is same as your link name For e.g. yourwebsite.com/Menu1
function setNavigation() {
var n = window.location.pathname,t;
n = n.replace("/", "");
t = $("ul li:contains(" + n + ")");
t.addClass("active");
}
You can than define styling in your active class as you like.
I stumbled upon this when googling for something similar. I have a JQueryUI accordion menu. My menu is in an included script (classic asp), so it is on every page but I think it is a similar situation. I cobbled something together based on SJ-B's answer (don't know why it was down voted).
I have this:
function saveSession(id) {
if (window.sessionStorage) {
sessionStorage.activeMenu = $("#jqmenu").accordion("option", "active") ;
sessionStorage.activeLink = id ;
}
}
and this
$(function() {
//give every li in the menu a unique id
$('#jqmenu a').attr('id', function(i) {
return 'link'+(i+1);
});
var activeMenu = 0;
var activeLink = "";
if (window.sessionStorage) {
activeMenu = parseInt(sessionStorage.activeMenu);
activeLink = sessionStorage.activeLink;
}
$("#" + activeLink).parent().addClass("selectedmenu");
$("#jqmenu").accordion({collapsible: true, active: activeMenu, heightStyle: "content", header: "h3"});
$("#jqmenu a").click(function() { saveSession($(this).attr('id')); });
});
OK, a bit untidy and cobbled together from various suggestions (I'm still learning), but it seems to work. Tried on IE11 and Firefox. Chrome can't find localhost but that's another story.
add lines below
<script>
$(function(){
$("a[href='"+window.location+"']").addClass("selected");
});
</script>
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");
$('.nav li').each(function () {
if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
$(this).addClass('active');
}
});

JQuery Show/Hide Link

So here is my dilemma. Been trucking on this Jquery extreme code here and I need help telling if a certain link is showing or not. Here is what I have.
The toggles:
<span class="icon icon84"></span>
<span class="icon icon85"></span>
(notice the only thing that is different is the icon number) These need to toggle back and forth when someone clicks the #visbilitybutton. Not sure of the best way to do this and to capture what is selected as well.
The only code I have currently makes the toggle go one way, but doesn't go back when clicked again.
$(document).ready(function () {
$('#visbilitybutton').click(function() {
$(this).replaceWith('<span class="icon icon85"></span>');
});
});
First things first, you shouldn't have multiple identical id attributes on your page. Make visibilitybutton a class.
Anyways, you can use the jQuery toggle() function to specify what to do on each consecutive click:
$(".visibilitybutton").toggle(function(){
$(this)
.attr("title","Invisible")
.find("span").toggleClass("icon84 icon85");
}, function(){
$(this)
.attr("title","Visible")
.find("span").toggleClass("icon84 icon85");
});
If you want to be more efficient, you can do it all in one fell jQuery swoop like so, with some good techniques:
var vis = ["Invisible","Visible"];
$(".visibilitybutton").click(function(){
var i = 0;
$(this)
.attr("title",vis[i])
.find("span").toggleClass("icon84 icon85");
i = (i==0)?1:0;
});
Even more so would be to make a class that hides the element when added to it and shows it when you remove it (a classname with display:none applied in the CSS works fine):
$(".visibilitybutton").click(function(){
$(this)
.toggleClass("hide")
.find("span").toggleClass("icon84 icon85");
});
You need to have unique ids; therefore, you should select the items by class. You can use toggle() to handle the consecutive clicks, and you can use toggleClass() to handle the swapping of classes.
HTML:
<span class="icon icon84"></span>
<span class="icon icon85"></span>
Javascript:
$(document).ready(function () {
$('.button').toggle(function() {
var $button = $(this);
$button.prop("title","Invisible");
$button.find('.icon85').toggleClass('icon85', 'icon84');
}, function() {
var $button = $(this);
$button.prop("title","Visible");
$button.find('.icon85').toggleClass('icon84', 'icon85');
});
});
The id attribute is supposed to be unique to each element. Change the id attribute to the class attribute for each hyperlink.
Then, in your jQuery code, get the hyperlinks by their class name:
$('.visbilitybutton').click(function() {
// code goes here
});
In your event handler, you should use test the title attribute, like so:
$('.visibilitybutton').click(function() {
$this = $(this);
if ($this.attr("title") == "Visible")
$this.attr("title", "Invisible").find("span")
.removeClass("icon85").addClass("icon84");
else
$this.attr("title", "Visible").find("span")
.removeClass("icon84").addClass("icon85");
});

Categories

Resources