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 :)
Related
I created a page that displays post with comments using ajax
To view the comments user must click comment button correspond to the post
For simple understanding, example:
In HTML
Block
<button id="btn1">cmt1</button>
<button id="btn2">cmt2</button>
<div id="cmt1">comments</div>
<div id="cmt2">comments</div>
'
I tried of using for loop as
for(var i=0;i<count;i++){
$("#cmt"+i).hide();
$("#cmtbtn"+i).click(function(){
$("#cmt"+i).toggle('slow');
});
}
But It works well for the last cmtbtn only and whenever i click all other buttons last comment box only displays
I'm saying that is there is a way of for loop or any looping
Update: My Js file is here http://jsfiddle.net/9ss50nzc
Try to give a same and unique class to all "Comment Button" and also to "Comment Div". Like example bellow :
<button id="btn1" class="comtbtn"> cmt1 </button>
<button id="btn2" class="comtbtn"> cmt2 </button>
<div id="cmt1" class="comt-div">comments1</div>
<div id="cmt2" class="comt-div">comments2</div>
Then catch the click event on class "comtbtn" . Bellow is the js script to hide show of comment -
$('.comtbtn').click(function() {
var btnId = $(this).attr("id");
var id = btnId.slice(-1);
$( "#cmt"+id ).toggle( "slow" );
});
Add css to hide all the comment section when initially loaded to the DOM.
.comt-div{
display:none;
}
Is this the sort of thing you want? A means of getting the index of the button which is equivalent to the indexed position of the hidden comment on your document?
You just hide the previous comment and display the new comment.
var oldNode = '';
function showComment = function(index) {
if (typeof oldNode != undefined) $(oldNode).hide('slow');
$('.comment:eq('+$(index).index()+')').show();
oldNode = $('comment:eq('+$(index).index()+')');
}
<button onclick="showComment(this)">cmnt 1</button>
<button onclick="showComment(this)" >cmnt 2</button>
<div class='comment' style='display: none'>comment a</div>
<div class='comment' style='display: none'>comment b</div>
Start with giving your buttons and divs classes
<button id="btn1" class="actionButtons">cmt1</button>
<button id="btn2" class="actionButtons">cmt2</button>
<div id="cmt1" class="actionDivs" style="display:none">comments1<br/>more comments<br/>and even more</div>
<div id="cmt2" class="actionDivs" style="display:none">comments2<br/>another comment<br/>and another one</div>
Then loop through elements with that class name
for(var i = 0; i < $(".actionButtons").length; i++){
$(".actionButtons")[i].onclick = function () {
for(var j = 0; j < $(".actionDivs").length; j++){
if ($(".actionDivs")[j].id == this.innerText)
$("#" + this.innerText).show();
else
$("#" + $(".actionDivs")[j].id).hide();
}
};
}
Fiddle
I hope this takes you closer to your solution.
I got the answer it is possible to toggle inside loop by using traversing. Thanks everyone finally I sort out the answer.
I have this div
<div class="newDiv">
It is generating in loop, something like
<div class="newDiv">
<div class = "innerDiv">
SomeCode
</div>
</div>
<div class="newDiv">
<div class = "innerDiv">
SomeCode
</div>
</div>
<div class="newDiv">
<div class = "innerDiv">
SomeCode
</div>
</div>
Now I want to add another class "BrightDiv" with the div that generated at odd places like
with first and third div.
what should I do to add Class "BrightDiv" along with "newDiv" with every div at odd place?
Try this : You can use :odd or :even to select odd / even elements, but it is depend on the index position and not natural number count. So In your case, you want first and third position div i.e. with index= 0 and 2 which is even by index position and hence use :even.
$('div.newDiv:even').addClass('BrightDiv');
DEMO
You can use filter to select only the odd indexed divs
$(".newDiv").filter(function() {
return $(this).index() % 2 == 1;
}).addClass("BrightDiv");
this will give you a solution $("div:even").addClass("BrightDiv");
Ways to achieve this:
CSS:
.newDiv:nth-child(odd) { /*CSS*/ }
or
.newDiv:nth-child(2n-1) { /*CSS*/ }
jQuery:
$('.newDiv:odd').addClass('BrightDiv');
I have 5 divs that contain copy.
I have a back and next button, to display each div.
Back | Next
<div class="vote-result first">
this is example copy
</div>
<div class="vote-result">
this is some more copy
</div>
<div class="vote-result">
some more copy
</div>
<div class="vote-result">
this is the last div
</div>
// hide the divs, except the first one.
.vote-result { display: none; }
.vote-result.first { display: block; }
The first time the next button link is clicked, I want to remove the off class, to show it as clickable, I probably should disable the link initially too and re-enable it too.
$(".back-btn").removeClass("off");
Once I display the last div, I need to add the off class to the next-btn and disable it.
I thought about using a carousel js plugin to accomplish this, but it is overkill for now.
I know of a way to do this, but it would involve assigning subclasses to the links based on what next or back button was clicked, so it will know what div to show next, as well as removing or adding the off class to the links.
I am hoping to find a solution that allows me to add more div's to display without modifying the code. Any help is appreciated, thank you.
Here is solution for you. I have created Fiddle for your requirement.
HTML code:
<a class="back-btn off">Back</a> | <a class="next-btn">Next</a>
<div class="vote-result first selectedDiv">
this is example copy
</div>
<div class="vote-result">
this is some more copy
</div>
<div class="vote-result">
some more copy
</div>
<div class="vote-result last">
this is the last div
</div>
JS/JQuery Code:
$(".back-btn").click(function(){debugger;
var prevElement=$('.selectedDiv').prev();
prevElement.show();
$(".selectedDiv").hide();
$(".selectedDiv").removeClass("selectedDiv");
prevElement.addClass("selectedDiv");
if($('.first').css('display')=="block"){
$(".back-btn").addClass("off");
}
else{
$(".next-btn").removeClass("off");
}
});
$(".next-btn").click(function(){debugger;
var nextElement= $('.selectedDiv').next();
nextElement.show();
$(".selectedDiv").hide();
$(".selectedDiv").removeClass("selectedDiv");
nextElement.addClass("selectedDiv");
if($('.last').css('display')=="block"){
$(".next-btn").addClass("off");
}
else{
$(".back-btn").removeClass("off");
}
});
CSS code:
.vote-result { display: none; }
.vote-result.first { display: block; }
.off{display:none;}
Your HTML file:
<html>
<head>
<style>
.vote-result { display: none; }
.vote-result.first { display: block; }
.off {
color: Red;
}
a {
color: blue;
}
</style>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="code.js"></script>
</head>
<body>
Back | Next
<div class="vote-result first">
this is example copy
</div>
<div class="vote-result">
this is some more copy
</div>
<div class="vote-result">
some more copy
</div>
<div class="vote-result">
this is the last div
</div>
</body>
</html>
Your new "code.js" file in the same directory:
/**
* The zero-based index of the <div class="vote-result"> element that is currently being shown
* #var {Number}
*/
var activeIndex = 0;
function getNumberOfItems() {
return $('.vote-result').length;
}
function synchronizeInterface() {
var numberOfItems = getNumberOfItems(),
lastIndex = numberOfItems - 1;
$('.vote-result').removeClass('first');
$('.vote-result').each(function(index) {
if (index == activeIndex) {
$(this).addClass('first');
}
})
$('.back-btn').toggleClass('off', activeIndex == 0);
$('.next-btn').toggleClass('off', activeIndex == lastIndex);
}
$(function() {
$('.back-btn,.next-btn').on('click', function() {
// If the button clicked is not deactivated
if (!$(this).hasClass('off')) {
// Determine whether the "Next" button was clicked (otherwise "Back" was clicked)
var clickedNext = $(this).hasClass('next-btn');
// Move the active index in the appropriate direction while not allowing it to fall outside the boundaries of appropriate indices
activeIndex = clickedNext
? Math.min(activeIndex + 1, getNumberOfItems() - 1)
: activeIndex = Math.max(0, activeIndex - 1);
// Make sure the interface now reflects the updated JavaScript variables
synchronizeInterface();
}
return false;
});
});
Some notes: You had an unclosed double-quote for one of your class attributes in your provided HTML. Also, I added some additional styling -- you may want to rename the ".first" CSS class to ".active" instead.
take a look at jquerys .next() function for navigating - jQuery - Next(). you can also check for the last item like this.
if($(this).is(':last-child'))
{
$('.next-btn').removeClass('off');
}else{
$('.next-btn').addClass('off');
}
check everytime a navigation button is clicked and do the same for the first button
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);
};
I am very new to javascript and I'm learning everyday from your community.
However, I can't find a clean solution for my current problem.
I have a grid of tiles on the first slide of a slideshow, and I want each one to link to the respective slide. For example the tile with classname "linkSlide3" goes to slide "3". Now I want to avoid repeating the following function which is working at the moment:
$('.linkSlide3').click(function() {
$('.slider').mySuperSlider('goTo', 3);
return false;
});
I need to increment from 1 to 20, how can I write it nicely please?
Thank you very much for your help! :-)
For such situations I use data attributes to refer corresponding elements:
$('.linkSlide').click(function() {
$('.slider').mySuperSlider('goTo', $(this).data('slide'));
return false;
});
And in HTML you add data-slide attribute to each repeating element:
<a class="linkSlide" data-slide="3">...</a>
Here is abstract example of how such a binding can work: http://jsfiddle.net/rNvKe/
Instead of naming your action buttons
.linkSlide1
.linkSlide2
.linkSlide3
.etc...
you can just do
.linkslide
and make sure that there's no other element inside the parent of your buttons,
that way your .linkslide elements will be organized by index from 0 to 19 (for 20 buttons).
Than go grab the .index() of the clicked button and send it to .superSlider( THAT INDEX!! ).
To animate your slider than you can just multiply that retrieved index by one-slide-width:
LIVE DEMO
jQuery:
$('.linkSlide, .back').click(function() {
var ind = $(this).index()+1; // +1 cause we are already at 0
if($(this).hasClass('back')) ind = 0; // go to slide index 0
superSlider( ind );
});
function superSlider( ind ){
var oneSlideWidth = $('.slide').width();
$('#allSlides').stop().animate({left: -(ind*oneSlideWidth) },700);
}
HTML:
<div id="slider">
<div id="allSlides">
<div class="slide"> <!-- index = 0 -->
Slide 0
<button class="linkSlide">Tile index 1</button> <!-- index = 0, add 1-->
<button class="linkSlide">Tile index 2</button> <!-- index = 1, add 1 -->
<button class="linkSlide">Tile index 3</button> <!-- index = 2, add 1 -->
</div>
<div class="slide"> <!-- index = 1 -->
Slide 1
<button class="back">Back to 0</button>
</div>
<div class="slide"> <!-- index = 2 -->
Slide 2
<button class="back">Back to 0</button>
</div>
<div class="slide"> <!-- index = 3 -->
Slide 3
<button class="back">Back to 0</button>
</div>
</div>
</div>
CSS:
#slider{
position:relative;
width:100px;
height:95px;
background:#eee;
text-align:center;
overflow:hidden;
}
#allSlides{
position:absolute;
left:0;
width:9999px;
height:95px;
}
.slide{
position:relative;
width:100px;
height:95px;
float:left;
}
Explore the jQuery methods I used:
http://api.jquery.com/click/
http://api.jquery.com/index/
http://api.jquery.com/hasclass/
http://api.jquery.com/width/
http://api.jquery.com/stop/
http://api.jquery.com/animate/
This was my first question on this website, and I didn't expect so many detailed answers… so quickly!
So thanks to all of you, for your time, skills and kindness!
I followed dfsq answer and it worked fine :-)
HTML:
<div class="linkSlide" data-slide="1"></div>
<div class="linkSlide" data-slide="2"></div>
<div class="linkSlide" data-slide="3"></div>
etc… until 20
JS:
$('.linkSlide').click(function() {
$('.slider').mySuperSlide('goTo', $(this).data('slide'));
return false;
});