How to change the number within an element ID upon each click? - javascript

I have a 7 divs and 1 "Next" button, where I'm trying to come up with a solution so each time the "Next" button is clicked, the current div slides up and the next div slides down. At the end, it would go back to the 1st div.
HTML:
<div id='selection_1'>selection_1</div>
<div id='selection_2' style='display:none'>selection_2</div>
<div id='selection_3' style='display:none'>selection_3</div>
<div id='selection_4' style='display:none'>selection_4</div>
......
<div id='selection_7' style='display:none'>selection_7</div>
<button type='button'>Next</button>
JS:
$(function(){
$("#next").click(function () {
$('#selection_1').slideUp();
$('#selection_2').slideDown();
});
});
But I got stuck since it only can only work once. I can't click next again to get selection_3 to show up, not to mention having it return to selection 1 when a round is finished.
I'm pretty new to JQuery so any advice is appreciated!

Store index in some global variable and use it to generate id, also assign id to next button
Live Demo
$(function(){
currentNum = 1;
$("#selection_1").show();
$("#next").click(function () {
$('#selection_' + currentNum).slideUp();
if (currentNum > 7) currentNum = 0;
$('#selection_' + (currentNum+1)).slideDown();
currentNum++;
});
});

Use this function it may help you
$(function(){
var count=1;
$("#next").click(function () {
$('#selection_'+count).slideUp();
$('#selection_'+(count+1)).slideDown();
count+= 1;
if(count==7){
count=1;
}
});
});

Check this Demo Fiddle.
$(function(){
var current = 1;
$('div[id^="sel"] div').hide();
$('#selection_1 div').slideDown();
$("#next").click(function () {
current++;
$('#selection_'+(current-1)+' div').slideUp();
$('#selection_'+current+' div').slideDown();
});
});
At start, Display just 1st <div>, and keep on incrementing the number on click of next.

Related

Carousel Thumbnail style not auto updating on prev click

I got this wonderful pieve of code to auto update my thumbnails on click and on bs.slide function. It works properly when auto updating via the timer interval, clicking the next arrow, or clicking on the respective thumbnail in the carousel.
$('#myCarousel').carousel({
interval: 4000
});
var selectorIdx = 1;
var numItems = 12;
// handles the carousel thumbnails
$('.carousel-selector').click(function () {
selectorIdx = $(this).closest('li').index();
$('#myCarousel').carousel(selectorIdx)
});
$('#myCarousel').on('slide.bs.carousel', function () {
$('#myCarousel')
.find('.carousel-selector')
.removeClass('selected')
.eq(selectorIdx).addClass('selected')
.end()
.find('.item').removeClass('selected')
.eq(selectorIdx).addClass('active');
if (selectorIdx < (numItems - 1)) {
selectorIdx++;
}
else {
selectorIdx = 0;
}
});
However the carousel thumbs do not auto update when the prev arrow is clicked, how can this code be updated to reflect that action?
Rough Fiddle, you can see when you hit the prev arrow the thumbs still update going forward instead of backward.
http://jsfiddle.net/gward90/xr8qzxmg/12/
Thank You
Here is how I would change your code to select the thumbnail. http://jsfiddle.net/xr8qzxmg/15/
$('#myCarousel').on('slide.bs.carousel', function (e) {
selectorIdx = $(e.relatedTarget).index();
$(this)
.find('.carousel-selector').removeClass('selected')
.eq(selectorIdx).addClass('selected')
.end()
.find('.item').removeClass('selected')
.eq(selectorIdx).addClass('active');
});

faking a Gif with javascript/jquery

I have a function that hides and shows divs on scroll based on pageY position, but I also need the ability to have it automatically hide and show divs in order(only the ones with children), sort of like a fake animated Gif, looping forever.
I tried this:
function autoPlay() {
$('.conP').each(function(){
if ($(this).children().length > 0) {
setInterval(function(){
$(this).show().delay('100').hide();
},300);
}
});
}
which is not returning any errors, but it's not hiding or showing any of the divs with class="conP".
Any suggestions as to what I'm doing wrong/how I could improve this?
try this -
function autoPlay() {
$('.conP').each(function(){
if ($(this).children().length > 0) {
var $that = $(this);
setInterval(function(){
$that.show().delay('100').hide();
},300);
}
});
}
You have an incorrect reference to this in your setInterval closure. Refer to "How this works" in JavaScript Garden.
In your case you should save the reference to this in a variable:
$('.conP').each(function() {
var $element = $(this);
setInterval(function () {
$(element).show().delay('100').hide();
}, 300);
});
Or, better use the first argument passed to each, which is equal to $(this) in this case.
Not sure it's a great idea to run intervals inside loops, but I'm guessing the issue is scope inside the interval function :
function autoPlay() {
$('.conP').each(function(i, elem){
if ( $(elem).children().length ) {
setInterval(function(){
$(elem).show().delay(100).hide();
},300);
}
});
}
I really appreciate all the help guys, I seem to have figured out the animation part:
setInterval( function() {
autoPlay();
},120);
function autoPlay() {
var backImg = $('#outterLax div:first');
backImg.hide();
backImg.remove();
$('#outterLax').append(backImg);
backImg.show();
}
By hiding whichever div is first, and removing it from-then appending it back into-the containing div, and showing the new first div, it animates quite nicely!

Click Function "this" not working

I have a script that I found at http://www.red-team-design.com/cool-notification-messages-with-css3-jquery, but I'm having a problem with my code
I'm wanting to get it to 1) hide on click, and 2) hide after 15 seconds
HTML:
<div class="warning message">It is currently past 4pm. Any orders placed between now and midnight will not be placed until 4pm tomorrow.</div>
Javascript:
var myMessages = ['info','warning','error','success']; // define the messages types
function hideAllMessages(){
var messagesHeights = new Array(); // this array will store height for each
for (i=0; i<myMessages.length; i++){
messagesHeights[i] = $('.' + myMessages[i]).outerHeight(); // fill array
$('.' + myMessages[i]).css('top', -messagesHeights[i]); //move element outside viewport
}
}
function showMessage(type){
hideAllMessages();
$('.'+type).animate({top:"0"}, 500);
setTimeout(function(){
$('.'+type).animate({top: -$('.'+type).outerHeight()}, 500);
hideAllMessages();
},15000);
}
$(document).ready(function(){
// Initially, hide them all
hideAllMessages();
// Show message
for(var i=0;i<myMessages.length;i++) {showMessage(myMessages[i]);}
// When message is clicked, hide it
$('.message').click(function(){
$(this).animate({top: -$(this).outerHeight()}, 500);
});
});
This is getting executed by php, which I'm just inserting the following line into my code using php:
<script type='text/javascript'>
$(document).ready(function(){
showMessage(warning)
});
</script>ā€‹
Now for some reason the div doesn't hide when I click it, and it won't hide after the 15 seconds as specified.
I've created a JSFiddle at http://jsfiddle.net/dpdesignz/yTaRa/1/ if anyone would mind looking to see what may be going wrong? I have a feeling it's related to the part executed by the PHP echo, so does anyone know of another way to maybe do this?
You have a few errors in your code.
First warning is not defined
Which refers to the following:
$(document).ready(function(){
showMessage(warning)
});
warning is not a set variable. Perhaps you mean this to be 'warning'.
Secondly showMessage is not defined
showMessage('warning');
This is called before the showMessage() function is defined. You can fix this by moving this call into the other $(document).ready()
http://jsfiddle.net/yTaRa/5/
var myMessages = ['info','warning','error','success']; // define the messages types
function hideAllMessages(){
var messagesHeights = new Array(); // this array will store height for each
for (i=0; i<myMessages.length; i++){
messagesHeights[i] = $('.' + myMessages[i]).outerHeight(); // fill array
$('.' + myMessages[i]).css('top', -messagesHeights[i]); //move element outside viewport
}
}
function showMessage(type){
hideAllMessages();
$('.'+type).animate({top:"0"}, 500);
setTimeout(function(){
$('.'+type).animate({top: -$('.'+type).outerHeight()}, 500);
hideAllMessages();
},15000);
}
$(document).ready(function(){
// Initially, hide them all
hideAllMessages();
// Show message
for(var i=0;i<myMessages.length;i++) {showMessage(myMessages[i]);}
// When message is clicked, hide it
$('.message').click(function(){
$(this).animate({top: -$(this).outerHeight()}, 500);
});
showMessage('warning');
});
ā€‹
$(document).ready(function(){
$('.info, .warning, .error, .success').hide();
$('.info, .warning, .error, .success').slideDown(500);
$('.info, .warning, .error, .success').delay(15000).slideUp(500);
$('.info, .warning, .error, .success').on('click', function() {
$(this).hide();
});
});
Let jQuery do all the work =)
http://jsfiddle.net/yTaRa/8/
If every message type will also be classed as message we can reduce this code down even further...
$(document).ready(function(){
$('.message').hide();
$('.message').slideDown(500);
$('.message').delay(15000).slideUp(500);
$('.message').on('click', function() {
$(this).hide();
});
});
http://jsfiddle.net/yTaRa/9/
$(document).ready(function(){
setTimeout(function() { //sets a 15 second timer on each message to collapse up over .5 seconds
$('.message').slideUp(500);
}, 15000);
$('.message').hide(); //hides all elements with the class message.
$('.message').slideDown(500); //animates messages to expand down over .5 seconds
$('.message').on('click', function() { //wires up click event to hide message on click
$(this).slideUp(500);
});
});
http://jsfiddle.net/yTaRa/10/
I had to use setTimeout for the 15 seconds call of slideUp as the click slideUp would not fire with:
$('.message').delay(15000).slideUp(500);
I assume that this is because only one slideUp() call can be scheduled on the same element at one time.

setInterval advance to next div when timer has cycled

I've been fiddling with this:
http://jsfiddle.net/bXJhe/46/
What I need is for the time to advance to the next div id after timer has cycled. I click on "one" and it shows the current id, then it should advance to "two", "three"... and show their respective ids. I do not want to use jQuery's .remove() or .detach(). Any insight would be fantastic.
Have a big project due, and no hair left to pull out.
HTML:
<span id="bar"></span>
<span id="timer">00:05</span>
<div id="one">one</div>
<div id="two">two</div>
<div id="three">three</div>
<div id="four">four</div>
JS:
jQuery(document).ready(function() {
jQuery('div').not(':first').hide();
jQuery('a').hide();
timer(5)
});
// Timer
var GLOBAL_TIMER;
function timer(intCount) {
GLOBAL_TIMER = setInterval(function() {
var intTickLength = 5;
jQuery('#bar').css('width', intCount * intTickLength + 'px');
jQuery('#timer').html('00:0' + intCount--);
if (intCount < 0) {
jQuery('a').show('slow');
jQuery('a').click(function() {
id = jQuery(this).parent('div').attr('id');
alert('current id: ' + id);
jQuery(this).hide();
timer(5);
});
stopTimer();
}
}, 1000);
}
function stopTimer() {
clearInterval(GLOBAL_TIMER);
}
Check and see if this is what you need:
jQuery(document).ready(function() {
jQuery('div').hide();
currDiv = jQuery('#one');
timer(5);
});
// Timer
var GLOBAL_TIMER;
function timer(intCount) {
GLOBAL_TIMER = setInterval(function() {
var intTickLength = 5;
jQuery('#bar').css('width', intCount * intTickLength + 'px');
jQuery('#timer').html('00:0' + intCount--);
if (intCount < 0) {
currDiv.show('slow');
currDiv.click(function() {
id = currDiv.attr('id');
alert('current id: ' + id);
jQuery(this).hide();
currDiv = currDiv.next();
timer(5);
});
stopTimer();
}
}, 1000);
}
function stopTimer() {
clearInterval(GLOBAL_TIMER);
}
The cleanest solution, I think, is to use jQuery's data() mechanism to attach a variable to each <div>, signaling that it's the next one to be shown.
Also, you have <a> elements inside your <div> elements, and you're sometimes trying to show/hide one or the other...it seems to me it would be clearer to always operate on the same element. I chose the <div> elements.
So, first you'll want to hide all your <div> elements:
jQuery('div').hide();
Then you'll want to indicate that the "one" <div> is the next one to be shown:
jQuery('#one').data('nextToBeShown',true);
Then when you're going through each element (I go through <div>s instead of <a>s), you just have to look to see if it's the next element to be shown, and show it:
jQuery('div').each(function() {
current = jQuery(this);
if( current.data('nextToBeShown') ) {
current.show('slow');
}
});
Finally, when you click on the link, you'll want to move the "nextToBeShown" pointer:
jQuery('a').click(function() {
id = jQuery(this).parent('div').attr('id');
alert('current id: ' + id);
div = jQuery(this).parent();
div.hide();
div.data('nextToBeShown',false);
div.next().data('nextToBeShown',true);
timer(9);
});
And that gets you where you want.... See my updated jsFiddle here: http://jsfiddle.net/NjUg2/1/
jsBin demo
Referring to my old answer and my old DEMO to you....
the only thing you need to add is this:
////////////// old answer :
(function($){ // remap "$" to jQuery
$(function(){ // "Document Ready" shorthand
var divCounter = 0; ///// added
function timer(bar, intCount){
var elWidth = $(bar).width(), intTickLength=intCount, i;
function math(){
var m = Math.floor(intCount/60);
var s = intCount % 60;
if(m<10){m='0'+m;}
if(s<10){s='0'+s;}
$(bar).next('.timer').text(m+':'+s);
$(bar).width( elWidth*intCount/intTickLength );
if(intCount--<=0){
clearInterval(i);
showDiv(); /////// added
}
}
math();
i = setInterval(math, 1000);
}
timer('#bar',5);
////////////////////////////////
///////////// new answer :
$('div.box').hide(); // hide all initially
function showDiv(){
$('.box').hide().eq(divCounter%$('.box').length).show();
}
$('.box a').click(function(e){
e.preventDefault();
$('.box').hide();
divCounter++;
timer('#bar',5);
});
/////////////////////////////
});
})(jQuery);
HTML: add a class .timer to your span
<span id="bar"></span>
<span class="timer">00:05</span>
and add a common CLASS to your div elements:
<div class="box">one</div>
<div class="box">two</div>
<div class="box">three</div>
<div class="box">four</div>
If you have questions feel free to ask, and don't pull more hair out, but review some old questions for some solutions :)

Toggle element's class by ID

Iā€™m trying to change the class of an element when it is clicked on from one value A to value B and then from value B back to value A when it is clicked a second time. I found some code on here that allowed me to change it once, but not a second time. (See original here).
Here is the original code:
<script type="text/javascript">
function changeClass() {
document.getElementById("MyElement").className += " MyClass";
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/(?:^|\s)MyClass(?!\S)/g, '')
}
</script>
And here is my code:
<script type="text/javascript">
function changeClass() {
if (document.getElementByID("arrow").className == "arrowdown") {
document.getElementById("arrow").className.replace(/(?:^|\s)arrowdown(?!\S)/g, 'arrowup')
}
elseif(document.getElementByID("arrow").className == "arrowup") {
document.getElementById("arrow").className.replace(/(?:^|\s)arrowup(?!\S)/g, 'arrowdown')
}
}
</script>
$('#arrow').toggleClass('arrowup arrowdown');
Why not simply use jQuery toggleClass instead along with a id selector?
$('#arrow').toggleClass('arrowup');
$('#arrow').toggleClass('arrowdown');
And save yourself debugging and a few lines of code!
Check this FIDDLE
Its far easier with JQuery..
$(function() {
var i = 0;
$('div').on('click', function() {
i++;
if( i % 2 == 0){
$(this).addClass('arrowup').removeClass('arrowdown');
}
else{
$(this).addClass('arrowdown').removeClass('arrowup');
}
});
});ā€‹
just use jquery addClass() and removeClass() or even better the toggleClass inside your click event
<div id="elemID" class="class1">
</div>
function changeClass()
{
$("#elemID").toggleClass("class1");
$("#elemID").toggleClass("class2");
}
REF's
http://api.jquery.com/addClass/
http://api.jquery.com/removeClass/
http://api.jquery.com/toggleClass/
Cheers
I faced something similar to this today. In my code for each feature the user would express his opinion by pressing thumbs up or thumbs down. The selected thumb icon would have a brighter color, so when the user would click the thumbs up icon, the thumbs up icon would turn green and the thumbs down icon (if it were green) would turn black.
I solved it using jQuery:
$(document).ready(function () {
$('#vote-yes-#(Model.ProductReviewId)').click(function () {
setProductReviewHelpfulness#(Model.ProductReviewId)('true');
$('#1vote-yes-#(Model.ProductReviewId)').toggleClass('green');
$('#1vote-no-#(Model.ProductReviewId)').removeClass('green').addClass('black');
});
$('#vote-no-#(Model.ProductReviewId)').click(function () {
setProductReviewHelpfulness#(Model.ProductReviewId)('false');
$('#1vote-no-#(Model.ProductReviewId)').toggleClass('green');
$('#1vote-yes-#(Model.ProductReviewId)').removeClass('green').addClass('black');
});
});

Categories