How can I properly use the 'eq' function on multiple classes? Because, the div's with class 'a' are not subsequent, I cannot use the 'eq' function to updated their class. If the divs with class "b", are removed, the function works perfectly. Here's a fiddle https://jsfiddle.net/9w8zhg7d/4/. I have the following HTML:
<div class="a current">
</div>
<div class="a">
</div>
<div class="b">
</div>
<div class="b">
</div>
<div class="a">
</div>
<div class="a">
</div>
and the following javascript:
Class = {
a: ".a",
highlighted: ".a.current",
init: function() {
$(this.a).click(this.toggleA.bind(this));
},
toggleA: function(e) {
e.preventDefault();
$(this.highlighted).removeClass("current");
var target = $(e.target);
var clickedA = target.closest(this.a);
var clickedIndex = clickedA.index();
$(".a").eq(clickedIndex).addClass("current");
console.log(clickedIndex);
$(".b").eq(clickedIndex).css("display", "inline-block");
}
};
Class.init();
Any help is much appreciated!
If I understand your question correctly, you want to know the index of the particular .a element that was clicked, ignoring all other elements. If so you just have to use the .index() method correctly:
var clickedIndex = $(this.a).index(e.target);
When you call .index() with no arguments as in your code, it finds the index of the first element in the jQuery object relative to its siblings, not relative to other elements in the jQuery object. The code I've shown says to first select all of the .a elements, then within those elements only figure out the position of the e.target element.
You've also overcomplicated the setting of the current class - it doesn't make sense to use .closest(), because that is for navigating up through the DOM and all of your elements are siblings. You can just say:
$(e.target).addClass("current");
I don't understand how you want to apply the index of the clicked .a element to the .b elements, because there are four .a's and only two .b's, but still putting what I've said above together with your code gives something like this:
Class = {
a: ".a",
highlighted: ".a.current",
init: function() {
$(this.a).click(this.toggleA.bind(this));
},
toggleA: function(e) {
e.preventDefault();
$(this.highlighted).removeClass("current");
var target = $(e.target).addClass("current");
var clickedIndex = $(this.a).index(e.target);
console.log(clickedIndex);
$(".b").removeClass("current").eq(clickedIndex).addClass("current");
$(".c").removeClass("current").eq(clickedIndex).addClass("current");
}
}
Class.init();
.a,.b { width:50px; height:50px; background:black; display:inline-block; }
.c { width:20px; height:20px; background:blue; display:inline-block; }
.a.current{ background:red; }
.c.current, .b.current{ background:green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="a current"></div>
<div class="a"></div>
<div class="b"></div>
<div class="b"></div>
<div class="a"></div>
<div class="a"></div>
<div class="related">
<div class="c"></div> <div class="c"></div> <div class="c"></div> <div class="c"></div>
</div>
(Or an updated version of your fiddle: https://jsfiddle.net/9w8zhg7d/8/)
Okay, I feel like the solution you're proposing may be overcomplicated. Have you considered this solution?
HTML:
<div class="container">
<div class="a current"></div>
<div class="a"></div>
<div class="b"></div>
<div class="b"></div>
<div class="a"></div>
<div class="a"></div>
</div>
CSS:
.container {
display: flex;
flex-wrap: wrap;
width: 100%;
}
.container > div {
width:50px;
margin: 1em;
height:50px;
background:black;
}
.a.current{
background:red;
}
Javascript:
$('.container > div').on('click', function() {
$('.container > div').removeClass("current");
$(this).addClass('current')
});
This will just apply .current to the one clicked and while removing it from all. Targeting the parent allows you to have that functionality without needing to work with the class specificity of the children div's.
JsFiddle: https://jsfiddle.net/9w8zhg7d/7/
Related
i am trying to toggle classes by using class name.
My code is working fine when i am toggling using id.
how can i make it work only one red should be visible at one time.
function hideshowmenu() {
var element = document.getElementsByClassName("box");
element.classList.toggle("bg-red");
}
.bg-red {
margin-top: 10px;
background-color: red;
height: 20px;
}
<div class="mainmenu " onclick="hideshowmenu()">RED1</div>
<div id="submenu" class="submenu">
<div class="mainmenu " onclick="hideshowmenu()">RED2</div>
<div id="box" class="box"> </div>
</div>
As the name of getElementsByClassName suggest, it returns elementS, so you are getting HTMLCollection, not one element. Query the first one, like this:
function hideshowmenu() {
var element = document.getElementsByClassName("box")[0];
element.classList.toggle("bg-red");
}
or:
function hideshowmenu() {
var elements = document.getElementsByClassName("box");
elements[0].classList.toggle("bg-red");
}
What is returned by document.getElementsByClassName("box"); is a collection. You need to specify the index to access the classList property.
You are doing:
var element = document.getElementsByClassName("box");
element.classList.toggle("bg-red");
When you should be doing
var element = document.getElementsByClassName("box");
element[0].classList.toggle("bg-red");
You could also loop through the elements if you want to toggle multiple values.
Example code fiddle
https://jsfiddle.net/agy5jtb0/1/
getElementsByClassName("box") return a collection of elements, but you considered it as a single element that is your mistake.
I suggest something like this:
html:
<div class="mainmenu " onclick="hideshowmenu(this)">RED1</div>
<div id="submenu" class="submenu">
<div class="mainmenu" onclick="hideshowmenu(this)">RED2</div>
<div id="box" class="box"></div>
</div>
js:
function hideshowmenu(el) {
el.classList.toggle("bg-red");
}
Check this (not sure If is this what you need):
function hideshowmenu() {
var elements = document.getElementsByClassName("box");
for (let a of elements) {
a.classList.toggle("bg-red");
}
}
.bg-red{
margin-top:10px;
background-color:red;
height:20px;
}
<div class="mainmenu " onclick="hideshowmenu(this)">RED1</div>
<div id="submenu" class="submenu">
<div class="mainmenu" onclick="hideshowmenu(this)">RED2</div>
<div id="box" class="box"></div>
</div>
I have a set of div elements inside a container, .div-to-hide is displayed by default whilst .div-to-show is hidden.
When I click in .set, .div-to-hide should hide and .div-to-show should be visible. Next click should return the previous clicked element to its default state.
I need to display to buttons on click inside on .div-to-show.
<div class="container">
<div class="set">
<div class="div-to-hide">Some text</div>
<div class="div-to-show"></div>
</div>
<div class="set">
<div class="div-to-hide">Some text</div>
<div class="div-to-show"></div>
</div>
<div class="set">
<div class="div-to-hide">Some text</div>
<div class="div-to-show"></div>
</div>
</div>
So far I have this:
let lastClicked;
$('.container').on('click', function(e) {
if (this == lastClicked) {
lastClicked = '';
$('.div-to-hide').show();
$(this).children('.div-to-hide').hide();
} else {
lastClicked = this;
$('.div-to-hide').hide();
$(this).children('.div-to-hide').show();
$(this).children('.div-to-show').hide();
}
});
Can't get it to work properly tho.. I don't know what I am missing...
Any help is deeply appreciated!
UPDATE: got it working! Thanks everyone!
First, you are not using delegation (second parameter on the $.on() function) to define the .set element as your this inside the function.
If I understood correctly, you want to show the elements on the last one clicked and hide the rest. You don't really need to know which one you last clicked to do that
$('.container').on('click', '.set', function (e) {
// Now "this" is the clicked .set element
var $this = $(this);
// We'll get the children of .set we want to manipulate
var $div_to_hide = $this.find(".div-to-hide");
var $div_to_show = $this.find(".div-to-show");
// If it's already visible, there's no need to do anything
if ($div_to_show.is(":visible")) {
$div_to_hide.show();
$div_to_show.hide();
}
// Now we get the other .sets
var $other_sets = $this.siblings(".set");
// This second way works for more complex hierarchies. Uncomment if you need it
// var $other_sets = $this.closest(".container").find(".set").not(this);
// We reset ALL af them
$other_sets.find(".div-to-show").hide();
$other_sets.find(".div-to-hide").show();
});
Consider using class toggling instead.
$('.set').on('click', function(e) {
$('.set').removeClass('hidden-child');
$(this).addClass('hidden-child');
});
css:
.hidden-child .div-to-hide, .div-to-show {
display: none;
}
.hidden-child .div-to-show, .div-to-hide {
display: block;
}
This will make your code easier to reason about, and lets css control the display (style) rules.
Edit: changed class name for clarity; expanded explanation; corrected answer to conform to question
Try to make use of siblings() jQuery to hide and show other divs and toggle() jQuery to show and hide itself and also you will need to set click() event on .set, not in .container
$(document).on('click', '.set', function(e) {
$(this).find('.hide').toggle();
$(this).find('.show').toggle();
$(this).siblings('.set').find('.hide').show();
$(this).siblings('.set').find('.show').hide();
});
.show {
display: none;
}
.set div {
padding: 10px;
font: 13px Verdana;
font-weight: bold;
background: red;
color: #ffffff;
margin-bottom: 10px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="set">
<div class="hide">1 Hide</div>
<div class="show">1 Show</div>
</div>
<div class="set">
<div class="hide">2 Hide</div>
<div class="show">2 Show</div>
</div>
<div class="set">
<div class="hide">3 Hide</div>
<div class="show">3 Show</div>
</div>
</div>
i want to hover over one div and use jquery to find the nearest div by the name and to show that div.
<div class="entry">
<div class="body"></div>
<div class="date"></div>
<div class="footer"></div>
<div class="body"></div>
<div class="date"></div>
<div class="footer"></div>
<div class="body"></div>
<div class="somethingelse"></div>
<div class="footer"></div>
</div>
all the .footer classes will be hidden but i want to make it so that when i over over the .body class, only the nearest .footer class shows. [ meaning : if i hover over the first .body class, only the first .footer will be shown. ]
my current code isn't working and i'm starting to wonder if it's something wrong with it.
current jquery code :
$('.footer').hide();
$('.body').hover(function(){
$(this).closest('.footer').find('.footer').show();
});
While the problem is the same as this question, the reason is slightly different.
When you use .closest(".class") it's the equivalent of .parents().filter(".class").first() (or .last(), I don't recall exactly which way parents() works as that's what closest is for).
ie it goes up the tree
So $(".body").closest(".entry") would give you an element for your HTML.
In this case, you want siblings, but more specifically the next one. There's a jquery method .next() which looks like it's correct, but as detailed in the link above, this only gives the very next one (in your HTML this would be the date div) even if a filter is applied - so $(this).next(".footer") would give an empty set (as it's not .date).
The work around is:
$(this).nextAll(".footer").first()
Once you get this working, your will find that your hover does not work as expected as the footers are not hiding again - as you're using .hover rather than mouseenter mouseout, you just need to move the .hide() call inside the second event handler, giving:
// startup
$(".footer").hide();
// event
$(".body").hover(function() {
$(this).nextAll(".footer").first().show();
}, function() {
$(".footer").hide();
});
div > div { width: 100px; height: 10px }
.body { border: 1px solid red; }
.date { border: 1px solid blue; }
.footer { border: 1px solid green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="entry">
<div class="body"></div>
<div class="date"></div>
<div class="footer"></div>
<div class="body"></div>
<div class="date"></div>
<div class="footer"></div>
<div class="body"></div>
<div class="somethingelse"></div>
<div class="footer"></div>
</div>
$(this).closest('.footer')
You should start to use console.log() sometimes to check elements you would like to get. This does not find anything so nothing further to search and to show.
If you possibly can separate bodies and footers into containers you can do smth like
this.
Try to make use of nextUntil(".footer").next(); as below
$('.body').hover(function() {
$(this).nextUntil(".footer").next().show();
}, function() {
$(".footer").hide();
});
body {
font: 13px Verdana;
}
.footer {
display: none;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="entry">
<div class="body">body</div>
<div class="date">date</div>
<div class="footer">footer</div>
<div class="body">body</div>
<div class="date">date</div>
<div class="footer">footer</div>
<div class="body">body</div>
<div class="somethingelse">somethingelse</div>
<div class="footer">footer</div>
</div>
IF your html is gonna keep those triads layout, you don't need jQuery for it.
Just use CSS to select the second div after the .body on hover
div{width:100px; height:100px; background-color:lime; margin:10px; float:left}
.body{background:yellow; clear:left;}
.footer{display:none;}
.body:hover + div + div{
display:block;
background:red;
}
<div class="body"></div>
<div class="date"></div>
<div class="footer"></div>
<div class="body"></div>
<div class="date"></div>
<div class="footer"></div>
<div class="body"></div>
<div class="somethingelse"></div>
<div class="footer"></div>
The answer by freedomn-m offered a good explanation and good solution in case you want the nearest NEXT .footer, which seems to be the case from your example HTML.
However, if you want your request strictly, so you want exact NEAREST .footer, then his solution will not work for you. And I don't think there is a jQuery built-in functionality that can give you that, so you'll have to do it manually. Get the list of the children of the parent (don't use the siblings as they don't include the current element) and go through the list to calculate the distance from your current element using the indexes and then select the .footer that is really the nearest.
$('.body').hover(function() {
var children = $(this).parent().children();
var index = children.index(this);
var closest = children.length;
var footer = -1;
children.each(function(i, child) {
if (i !== index && $(child).hasClass("footer")) {
var distance = Math.abs(index - i);
if (distance < closest) {
closest = distance;
footer = i;
}
}
});
if (footer > -1)
children.eq(footer).show();
}, function() {
$(".footer").hide();
});
body {
font: 13px Verdana;
}
.footer {
display: none;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="entry">
<div class="body">body</div>
<div class="date">date</div>
<div class="footer">footer</div>
<div class="body">body</div>
<div class="date">date</div>
<div class="footer">footer</div>
<div class="body">body</div>
<div class="somethingelse">somethingelse</div>
<div class="footer">footer</div>
</div>
If you don't care much about the performance, you can shorten the code a bit by selecting the list of .footer instead of the children of the parent, and then let jQuery give you the index of each of them. Not very efficient, but shorter code:
$('.body').hover(function() {
var index = $(this).index();
var closest = 9999;
var footer;
$(this).siblings(".footer").each(function(i, sibling) {
var distance = Math.abs(index - $(sibling).index());
if (distance < closest) {
closest = distance;
footer = sibling;
}
});
if (footer !== undefined)
$(footer).show();
}, function() {
$(".footer").hide();
});
body {
font: 13px Verdana;
}
.footer {
display: none;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="entry">
<div class="body">body</div>
<div class="date">date</div>
<div class="footer">footer</div>
<div class="body">body</div>
<div class="date">date</div>
<div class="footer">footer</div>
<div class="body">body</div>
<div class="somethingelse">somethingelse</div>
<div class="footer">footer</div>
</div>
Inspired by freedomn-m's comment, we can also use the .prevAll() and .nextAll() methods to get the previous and next .footer siblings. These two methords return the siblings ordered by the closest, so we simply pick the first one of each list, subtract their indexes from our element's index (to find the distance), compare them together, and return the closest. This solution is also less efficient than the first one, but you may find the code easier to read:
$('.body').hover(function() {
var me = $(this);
var prev = me.prevAll(".footer").first();
var next = me.nextAll(".footer").first();
if (prev.length == 0)
next.show();
else if (next.length == 0)
prev.show();
else {
index = me.index();
if (Math.abs(prev.index() - index) < Math.abs(next.index() - index))
prev.show();
else
next.show();
}
}, function() {
$(".footer").hide();
});
body {
font: 13px Verdana;
}
.footer {
display: none;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="entry">
<div class="body">body</div>
<div class="date">date</div>
<div class="footer">footer</div>
<div class="body">body</div>
<div class="date">date</div>
<div class="footer">footer</div>
<div class="body">body</div>
<div class="somethingelse">somethingelse</div>
<div class="footer">footer</div>
</div>
<div class="wrap">
</div>
my css
.wrap{
overflow-x:hidden;
}
should I do like this in js?
document.getElementById("whatever").className = "";
where to get the id in this case? since I use .wrap not #wrap.
I think you're looking for the DOM function getElementByClassName().
For example, if you run var x = document.getElementByClassName('wrap') in your case, x will be a list of all dom elements which have the class 'wrap' .
source: w3schools
Your question is a bit confusing, but to give you an easy example, have a look at this:
var divs = document.getElementsByClassName('wrap');
for (var i=0; i<divs.length; i++) {
divs[i].addEventListener('click', removemyclass);
}
function removemyclass () {
this.className = '';
}
.wrap {
height:50px;
width: 100%;
border: 2px solid #aaa;
}
<div class="wrap">
</div>
<div class="wrap">
</div>
<div class="wrap">
</div>
<div class="wrap">
</div>
<div class="wrap">
</div>
<div class="wrap">
</div>
<div class="wrap">
</div>
This will find the one ( this ) element you are clicking on and remove its class Name, so that it doesn't have a border anymore, but you can still find it in your console as an element in the DOM
I'm very new to javascript and jQuery and has now got completely stuck despite trying various options. I'm trying to create a expand/collapse section with multiple divs. I would like each div to open and close seperately, with an arrow at the side pointing up or down, depending whether the content is expanded or collapsed.
From the code I have written below, only the first div works correctly. The only thing which happen When you click on the two other divs, is that the arrow in the first div change.
Any help will be greatly appreciated.
Following is the CSS:
#header_background {
background-image: url(header-background.png);
width:748px;
height:43px;
margin-left: -17px;}
#expand_arrow {
display: inline-block;
width: 17px;
height: 18px;
float:left;
margin-left:20px;
padding-left:0px;
padding-top:11px;
background-repeat:no-repeat; }
.sub_header {
color:#204187;
font-weight:bold;
font-size:16px;
vertical-align:middle;
padding-left:4px;
padding-top:12px;
float:left;
text-decoration:none;
}
Here's the attempted javascript and jQuery:
function chngimg() {
var img = document.getElementById('expand_arrow').src;
if (img.indexOf('expand-arrow.png')!=-1) {
document.getElementById('expand_arrow').src = 'images/collapse-arrow.png';
}
else {
document.getElementById('expand_arrow').src = 'images/expand-arrow.png';
}
}
$(document).ready(function(){
$("#header_background").click(function(){
$("#section").slideToggle("slow");
});
});
And here's the HTML
<div id="header_background" >
<img id="expand_arrow" alt="" src="images/collapse-arrow.png" onclick="chngimg()">
<div class="sub_header" onclick="chngimg()">header 1</div>
</div>
<div id="section" style="display:none">
text 1
</div>
<div id="header_background" >
<img id="expand_arrow" alt="" src="images/collapse-arrow.png" onclick="chngimg()">
<div class="sub_header" onclick="chngimg()">header 2</div>
</div>
<div id="section" style="display:none">
text 2
</div>
<div id="header_background" >
<img id="expand_arrow" alt="" src="images/collapse-arrow.png" onclick="chngimg()">
<div class="sub_header" onclick="chngimg()">header 3</div>
</div>
<div id="section" style="display:none">
text 3
</div>
It's only working for the first set of elements because you're using IDs, and IDs have to be unique within the document (page). You could change to using classes and perform some simple DOM traversal to get the corresponding section based on the header that was clicked. Something like this:
$(document).ready(function() {
$('.header_background').click(function(e) {
$(this).next('.section').slideToggle('slow');
var img = $(this).find('img.expand_arrow')[0]; // the actual DOM element for the image
if (img.src.indexOf('expand-arrow.png') != -1) {
img.src = 'images/collapse-arrow.png';
}
else {
img.src = 'images/expand-arrow.png';
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header_background" >
<img class="expand_arrow" alt="" src="images/collapse-arrow.png">
<div class="sub_header">header 1</div>
</div>
<div class="section" style="display:none">
text 1
</div>
<div class="header_background" >
<img class="expand_arrow" alt="" src="images/collapse-arrow.png">
<div class="sub_header">header 2</div>
</div>
<div class="section" style="display:none">
text 2
</div>
<div class="header_background" >
<img class="expand_arrow" alt="" src="images/collapse-arrow.png">
<div class="sub_header">header 3</div>
</div>
<div class="section" style="display:none">
text 3
</div>
Look for your next section of the header clicked like so. And change your id for class because ID need to be unique
$(".header_background").click(function(){
$(this).nextAll(".section:first").slideToggle("slow");
});