I want to get the index of the clicked child
<div class="parent">
<div class="child">
<div class="c1"></div>
<div class="c2"></div>
</div>
<div class="child">
<div class="c1"></div>
<div class="c2"></div>
</div>
<div class="child">
<div class="c1"></div>
<div class="c2"></div>
</div>
</div>
jQuery:
$('.child .c1').click(function(){
alert($(this).parent().index())
})
I always get -1. How can i do this work?
EDIT:
I tried this:
$('.child .c1').click(function(){
alert($(this).index())
})
The result is -1 all the time.
What could be wrong?
var child_index = '';
$('.c1').click(function() {
var parent = $(this).parent();
child_index = $(parent).index();
alert(child_index);
});
.div{
position:absolute;
left:45%;
top:0;
}
.child{
margin:1%;
text-align:center;
background-color:gray;
width:100px;
height:100px;
}
.c1,.c2{
color:white;
background-color:blue;
}
.c2{
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div class="div">
<div class="child">
<div class="c1">c1</div>
<div class="c2">c2</div>
<p>click only work on <strong>c1</strong></p>
</div>
<div class="child">
<div class="c1">c1</div>
<div class="c2">c2</div>
<p>click only work on <strong>c1</strong></p>
</div>
<div class="child">
<div class="c1">c1</div>
<div class="c2">c2</div>
<p>click only work on <strong>c1</strong></p>
</div>
</div>
var child_index = ''; //to store .child class parent index when clicked
$('.c1').click(function() {
var parent = $(this).parent(); //getting the specific parent of c1
//parent variable value now is = .child
child_index = $(parent).index();
alert(child_index);
});
The reason that it returns -1 every time is because in Jquery -1 is a boolean for false and 0 is true. .index() basically asks whether an element exists.
If you want to find what number it is this is a code which I think would work.
var loop = $('.parent .child').length;
$('.child .c1').click(function(){
for(i=1; i<= loop; i++) {
if($(this).parent() === $('.parent').children().eq(i)) {
alert(i);
}
}
});
EDIT Since no one can reproduce the problem, here are some possibilities:
The version of jQuery you're using is conflicting with another script on your page. Since it seems your click event handler is firing because your getting an alert box.
Try using the latest version of jQuery.
Your version of jQuery is conflicting with the current browser you are using. When you're having JavaScript issues you should report the versions of the library you are using (if any) and of your browser.
Check your results in another browser and report back.
Your HTML is being manipulated before your click event is fired. What other code do you have on the page?
Share a more complete source code listing.
alert($(this).parent().prevAll().length);
Use .prevAll to get all previous siblings, then use the length of that set as your index.
edit Use .prevAll(".child") if you are expecting other elements that you want to ignore for indexing purposes.
edit You could try removing jQuery all together
var elms=document.getElementsByClassName("c1");
for(var i=0; i<elms.length; i++)
elms[i].onclick = function() {
var elm = this;
var index = 0;
elm = elm.parentNode;
if(elm) {
while(elm=elm.previousSibling) {
if(elm.nodeType == 1) {
index++;
}
}
} else {
alert("There's no parent node");
}
alert(index);
};
Related
In my project there are 10 divs with the class .content like this:
<div class="content">Example</div>
I have already wroted a function that will atribute an .active class to my divs and they will appear like this:
<div class="content active">Example</div>
Now i need a function than will verify if all my divs with the class .content have the class .active too.
Thank you.
you can get the list of div and check
var contentDivs = document.getElementsByClassName("content")
for (var i = 0; i < contentDivs.length; i++) {
var div = contentDivs[i];
if (div.classList.contains("active")) {
// do something
} else {
// do something
}
}
document.querySelectorAll(".content").forEach(e => {
console.log(e.classList.contains("active"));
});
<div class="content active">Example</div>
<div class="content">Example</div>
<div class="content active">Example</div>
<div class="content">Example</div>
<div class="content active">Example</div>
Here is an example.
Pass the elements to check in the following function :
function verify(elementX, nameOfStyleToCheck) {
return elementX.classList.contains(nameOfStyleToCheck);
}
On click, I want to get the name of the closest div and then look for all div's, that have this name attribute and add a class to them.
Here is my code:
HTML:
<div class="wrapper">
<div class="container" name="button1">
<div class="button">this is p #1</div>
</div>
</div>
<div name="button1">
somewhere else
</div>
JS:
$('.wrapper').on("click", '.button', function() {
var attrname = $(this).closest('.container').attr('name');
$("div[name=attrname]").each(function() {
$(this).addClass("classtobeadded");
});
});
But it is not working. So, how can I use the variable in here:
$("div[name=attrname]").each(function()
Here is the fiddle:
There's a few issues with your logic. Firstly the .container element does not have the name attribute, the .button does, so you don't need to use closest(). Secondly, you need to concatenate the actual name value in to the selector. Lastly div elements do not have a name attribute so the HTML is invalid. If you want to store custom meta-data on an element use a data attribute instead.
Also note that you don't need the each() loop, you can just call addClass() on the collection selected with the data-name attribute. Try this:
$('.wrapper').on("click", '.button', function() {
var attrname = $(this).data('name');
$('div[data-name="' + attrname + '"]').addClass("classtobeadded");
});
.classtobeadded {
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="container">
<div class="button" data-name="button1">this is p #1</div>
</div>
</div>
<div data-name="button1">
somewhere else
</div>
You have to concatenate it properly,
$(`div[name=${attrname}]`).each(function() {
And by the way, when looking at your code there is no attribute available in the closest div with a class .container. Check that as well.
$("div[name=" + attrname + "]").each(function() {})
or
$(`div[name=${attrname}]`).each(function() {})
I am trying to create the following.
I have a button and on click of that button i need to add some active class to a div, but i have 4 divs with same class. What am trying to create is like a Choose Bet system like when you click first time on button you choose the first bet, when second time the second, i have 4 bets.
My html structure is the below
<div class="game_paytable_bluebet_column game_paytable_column"></div>
<div class="three_bet_wrappaer">
<div class="game_paytable_greenbet_column game_paytable_column"></div>
<div class="game_paytable_orangebet_column game_paytable_column"></div>
<div class="game_paytable_redbet_column game_paytable_column"></div>
</div>
What i did so far with jquery see below
jQuery('.choose_bet_button').click(function(){
if(!jQuery('.game_paytable_column:first').hasClass('active_blue_bet')){
jQuery('.game_paytable_column:first').addClass('active_blue_bet');
}else{
jQuery('.game_paytable_column:first').removeClass('active_blue_bet');
jQuery('.game_paytable_column').next().addClass('active_blue_bet');
}
});
With this code it is getting 2 elements.
Any idea how to get a solution to this?
Thanks in advance.
Here is an interpretation, please see the comments for a breakdown.
jQuery('.choose_bet_button').click(function(){
// get all the elements that match your selector
var $columns = $('.game_paytable_column')
// get the currently active element
var $active = $columns.filter('.active_blue_bet')
// get the index of the active element relative to your columns
var index = $active.length ? $columns.index($active) : -1
// increment the index if there is a next element or reset to 0
var newIndex = ($columns.length > index + 1)
? index + 1
: 0
// remove the active class from all elements
$columns.removeClass('active_blue_bet')
// set the new active column
$columns.eq(newIndex).addClass('active_blue_bet')
});
.game_paytable_column {
width: 100%;
height: 40px;
margin: 4px;
background: #eee;
}
.active_blue_bet {
background: #bada55;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="game_paytable_bluebet_column game_paytable_column active_blue_bet"></div>
<div class="three_bet_wrappaer">
<div class="game_paytable_greenbet_column game_paytable_column"></div>
<div class="game_paytable_orangebet_column game_paytable_column"></div>
<div class="game_paytable_redbet_column game_paytable_column"></div>
</div>
<button class="choose_bet_button">choose</button>
Using :eq() you can achieve your requirement.
And initialize a counter and based on the counter add class in div.
And every four click make the counter 0.
Please check this snippet.
var _click = 0;
$('.choose_bet_button').click(function(){
if((_click % $(".game_paytable_column").length)==0){_click=0;}
$('.game_paytable_column').removeClass('active_blue_bet');
$('.game_paytable_column:eq('+_click+')').addClass('active_blue_bet');
_click++;
if($.trim($(".in_sight_area").html())==""){
$(".in_sight_area").html('<div class="top_bet_column_two top_bet_column game_paytable_column">New One</div>');
}
});
.active_blue_bet{
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="in_sight_area"></div>
<div class="game_paytable_bluebet_column game_paytable_column">1</div>
<div class="three_bet_wrappaer">
<div class="game_paytable_greenbet_column game_paytable_column">2</div>
<div class="game_paytable_orangebet_column game_paytable_column">3</div>
<div class="game_paytable_redbet_column game_paytable_column">4</div>
</div>
<br/>
<button class="choose_bet_button">Choose Bet</button>
<div class="game_paytable_redbet_column game_paytable_column">5</div>
If you have a button... i.e.:
<button onclick="next()" >NEXT</button>
Seems quite simple:
// get all elements with class game_paytable_column
var columns = document.getElementsByClassName("game_paytable_column");
// counter to control the actual index
var counter = 0;
function next() {
// this selects the actual element and shows content
alert(columns[counter].innerHTML);
//and passes to next element
if (counter == columns.length - 1)
counter = 0;
// first if necessary
else
counter ++;
}
WORKING DEMO
That's all :)
I have some javascript code for a FAQ page for my site. So, you click on the question and the answer appears. NOW, what I can't figure out is when I have clicked on one question and that is open, when I click on another I want the previous one to close. Basically, so there is only ever ONE open at a time. Found similar code, but not exactly what I'm looking for.
Any help would be great, here's my code. THANKS!!!! Kait
<script type="text/javascript">
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
</script>
<p>Here is my Question???</p>
<div id="q1" class="hidden">
<p>The Answer goes here.</p>
</div>
<p>Here is my 2nd Question???</p>
<div id="q2" class="hidden">
<p>The 2nd Answer goes here.</p>
</div>
use a variable to store a reference to the previously shown element, then hide it before showing the one you want to unhide
<script type="text/javascript">
var previous;
function unhide(divID) {
var item = document.getElementById(divID);
if (previous != null)
previous.className='hidden';
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
previous = item;
}
}
</script>
<p>Here is my Question???</p>
<div id="q1" class="hidden">
<p>The Answer goes here.</p>
</div>
<p>Here is my 2nd Question???</p>
<div id="q2" class="hidden">
<p>The 2nd Answer goes here.</p>
</div>
Example
http://jsfiddle.net/hLkks
Give all the answers a class name then select them all and hide them before you reveal the one that you just clicked. If you are using jQuery
$(".answers").addClass("hidden");
$("#"+id).removeClass("hidden");
There is a really simple approach. Improving on Wryte's answer, just add a click event to all items which adds a class to the active one and removes this from all the others.
item.addEventListener("click", function () {
var items = this.parentNode.childNodes;
for (var i=0; i < items.length; i++) {
items[i].className = "";
}
this.className = "active";
}, false);
Fiddle: http://jsfiddle.net/Met3T/
Each item can be whatever you like and you don't need any framework, just plain ole JavaScript.
The CSS could be simple as this:
li {
height: 2em;
background: green;
overflow: hidden;
margin-bottom: 5px;
}
.active {
height: auto;
}
<script type="text/javascript">
var currentItem;
function unhide(divID) {
if (currentItem) {
currentItem.className = 'hidden';
currentItem = null;
}
var item = document.getElementById(divID);
if (item) {
item.className = 'unhidden';
currentItem = item;
}
}
</script>
$(".header a.toggle").click(function(){
if($(this).hasClass("expanded")){
$(this).removeClass("expanded").addClass("collapsed")
.parent().siblings(".body").hide()
}
else{
$(this).removeClass("collapsed").addClass("expanded")
.parent().siblings(".body").show()
}
});
Heres a example where it looks if class is expanded or collapsed
<a class='toggle expanded' href='#'>Text</a>
So make a expanded and collapsed in your CSS
i use a simple bit of code to make a div collapse, this is it:
<script language="JavaScript">
<!--
function expand(param)
{
param.style.display=(param.style.display=="none")?"":"none";
}
//-->
</script>
what code do i add to make it recognise when one div is open an collapse the previous div?here's the link I'd use:
Link 1
<div id="div1" width="300px" style="display:none"></div>
Any ideas?
This is something jQuery works really well for. Here is a working example in jsfiddle.
http://jsfiddle.net/mrtsherman/uqnZE/
Example html
<div class="category">A
<div class="artists">Apple<br/>Ace<br/>Ants<br/></div>
</div>
<div class="category">B
<div class="artists">Bee<br/>Bop<br/>Book<br/></div>
</div>
<div class="category">C
<div class="artists">Cake<br/>Chimp<br/>Charles<br/></div>
</div>
And the code:
$(".category").click( function() {
$(".artists").hide();
$(this).children(".artists").show();
});
Basically what it does is hide all the divs that contain artists, then shows the div for the one you clicked on. Really simple.
If you were willing to use jQuery, the selector of your interest is something along the lines of
$('div#parent-container > div').filter(':visible');
For example, if I were to demonstrate with next & previous, I would do it something like this. With targeted links it would work by appending ID's to the divs and referencing those in the href attribute of `anchors'. (now included within example)
Something to mess with:
$(function(){
//Reference Object
var $divs = $('div > div');
//Buffer for selected variable
var $selected = 0;
//Show first
$divs.eq(0).show();
$('#next').click(function(){
//Update selected var
$selected = $divs.filter(':visible');
//Save next to variable
var $next = $selected.next();
//Change Visibility
toggle($next);
//Prevent Default
return false;
});
$('#prev').click(function(){
$selected = $divs.filter(':visible');
var $prev = $selected.prev();
toggle($prev);
return false;
});
$('a').click(function(){
$selected = $divs.filter(':visible');
var selector = $(this).attr('href');
if(selector == '#') return false;
toggle( $( selector ) );
return false;
});
var toggle = function($toggle){
if(!$toggle.length) return false;
$selected.hide();
$toggle.show();
}
});
<!--Simple Implementation and dependancies-->
<a id="prev" href="#">Prev</a>
<a id="next" href="#">Next</a>
Show Item Four
<div>
<div id="item-1">One</div>
<div id="item-2">Two</div>
<div id="item-3">Three</div>
<div id="item-4">Four</div>
<div id="item-5">Five</div
<div id="item-6">Six</div>
</div>
div > div {
font-size:5em;
width:auto;
text-align:center;
padding:20px 0;
display:none;
}