How to animate back my buttons - javascript

A small problem... I think!
I have a menu of buttons. When one clicked, it moves (animates). When another one is clicked, I need the first one to move back again.
So far they only moves when clicked, but not back again.
The code:
$(document).ready(function(){
var vari = $(this).attr('name');
$('.nav_btn').click(function(){
$(this).animate({left:'50%'});
});
});

With jQuery, this seems easy to me. What you do is, that you give all buttons same className and you loop through all of them when one of them is clicked. Because you can get element collection this will look much like this:
$(document).ready(function(){
var vari = $(this).attr('name');
$('.nav_btn').click(function(){
var buttons = $('.nav_btn');
for(var i=0; i<buttons.length; i++) {
if(buttons[i]!=this) //Avoid animating clicked button twice! Think of performance
$(buttons[i].animate({left:'0%'});
}
$(this).animate({left:'50%'});
});
});

Try this use .siblings() here:
$(document).ready(function(){
var vari = $(this).attr('name');
$('.nav_btn').click(function(){
$(this).animate({left:'50%'});
$(this).siblings().animate({left: '0'});
});
});
Working demo
Although not required but you can provide a animation duration of animate.

Related

How to programmatically click on button, THEN do something?

I'm trying to write a script where I programmatically click a tab, which reveals more divs on the website, and then perform some actions on those revealed divs.
Right now, I have
document.getElementById("buttonid").click(); // which reveals another section of the webpage
console.log($("#idofnewdiv"));
...but it doesn't seem to see the new div. However, when I manually click on the button, console.log is able to properly print it out. Am I doing something wrong?
var button = document.getElementById("buttonid");
button.addEventListener("click", function(){
alert("Button is Clicked");
});
button.click();
too you can use it like this:
var mButton = document.getElementById("buttonId");
mButton.onClick(function(){
your code to execute here.
});
It doesn't look like your click function is doing anything. The following code assumes that all of the <div>s are already hidden.
var listOfDivsToReveal = document.getElementsByClassName("divsToReveal");
var listOfDivsIter = 0;
$("#thebuttonID").click(function(){
if(listOfDivsIter > listOfDivsToReveal.length){
//do whatever you do when all of your <div> tags are revealed
}
listOfDivsToReveal[listOfDivsIter++].style.display = "inline";//Or your desired display.
});

JQuery/JavaScript hide one clicked element but not others

I'm creating a JavaScript and JQuery "Whack-a-Mole" game, and I'm appending "mole" images at random coordinates into the gamespace every two seconds. When a mole is clicked, I would like it to hide (disappear from the screen). However, the way I have the code written now, clicking on one mole causes all mole images to be hidden. Would love to hear any thoughts on selecting and hiding only the clicked mole image, but not hiding the other mole images.
Here's my "addMole" function:
function addMole() {
xPos = randPosX();
yPos = randPosY();
$('#gamespace').append('<img src="img/mole.png" style="top:'+yPos+'px;left:'+xPos+'px" />').addClass('mole'); // insert mole into #gamespace
repeatAddMole = setTimeout("addMole()", 2000); // append moles every 2 seconds
};
And here's the game's main function:
$(document).ready(function() {
$('#start_button').click(function() {
start();
$('#timer').show(); // show timer
$('.mole').on("click", function(){
incScore();
$('img', this).hide();
});
});
Thanks!
You are adding the mole class to the #gamespace, not the image. Maybe you want this:
$('#gamespace').append($('<img src="img/mole.png" style="top:'+yPos+'px;left:'+xPos+'px" />').addClass('mole'));
Here's a demo to help you https://jsfiddle.net/bradlis7/ubar2Lzb/1/. I like to keep the functions doing what they say they are doing (addMole should not really be setting a new timer).
You can do it like this:
$('#gamespace').append('<img onclick="this.style.display=\'none\'" src="img/mole.png" style="top:'+yPos+'px;left:'+xPos+'px" />').addClass('mole'); // insert mole into #gamespace
Also the problem is cause you attach event only to created images (moles) before you clicked on start.
You can use event delegation. Use this code out of start button click handler.
$( "#gamespace" ).on( "click", "img", function( event ) {
incScore();
$(this).hide();
});
I would do it pretty much in this way:
function addMole() {
xPos = randPosX();
yPos = randPosY();
var el = $('#gamespace').append('<img src="img/mole.png" style="top:'+yPos+'px;left:'+xPos+'px" />').addClass('mole');
el.on("click", function(){
$(this).remove();
incScore();
});
repeatAddMole = setTimeout("addMole()", 2000);
};
append function returns you jQuery object of appended element, so you can attach event directly on it after it is created. If you create events before objects are created, events will not be attached to it. This way, you create element and then attach the event.
You could do it in the way mhodges wrote in his comment, but I simply don't like this way because I believe it's not that efficient.

Deactivate part of page on click

I'm trying to create a quiz in the style of Buzzfeed. Is there a way to deactivate a part of the page when the user clicks on an answer, so that users can no longer click on alternative options of the same question and thus distort the final score of the test.
I've found some similar topics here and here but I don't want to add overlays and I'm not using inputs in my code so I was wondering if there is an alternative route.
I created a codepen here http://codepen.io/kkoutoup/pen/ByGEoQ
$(document).ready(function(){
//create an array to store correct answers
var totalCorrect = [];
$('li').click(function(){
//caching variables
var $parent = $(this).parent();
var $span = $(this).find('.fa');
//check for .correct class
//if yes
if($(this).hasClass('correct')){
//add .correctAnswer class
$(this).addClass('correctAnswer');
//find next span and change icon
$span.removeClass('fa fa-square-o').addClass('fa fa-check-square-o');
//reduce opacity of siblings
$(this).siblings().addClass('fade');
//show answerText
var $answerReveal= $parent.next('.answerReveal').show();
var $toShowCorrect = $answerReveal.find('.quizzAnswerC');
var $toShowFalse = $answerReveal.find('.quizzAnswerF');
$toShowCorrect.show();
$toShowFalse.remove();
//add 1 to total correct array
totalCorrect+=1;
//get array's length
var $finalScore = totalCorrect.length;
console.log($finalScore);
}else{
//add .wrongAnswer class
$(this).addClass('wrongAnswer').addClass('fade');
//change icon
$span.removeClass('fa fa-square-o').addClass('fa fa-check-square-o');
//reduce opacity of its siblings
$(this).siblings().addClass('fade');
//show wrong Message
var $answerReveal= $parent.next('.answerReveal').show();
var $toShowCorrect = $answerReveal.find('.quizzAnswerC');
var $toShowFalse = $answerReveal.find('.quizzAnswerF');
$toShowCorrect.remove();
$toShowFalse.show();
//locate correct and add respective class
$parent.find('.correct').addClass('correctAnswer');
};
});
});//end dom ready
Any ideas?
Thanks
What we're doing is removing the click function from the click event of the selected set of options - in this case, all the children of the elements parent. Thus when the user tries to click again, the click function would not be called on the click event.
Add the following line in click function because we want to trigger the disable as soon as any option is clicked on
$(this).parent().find('li').off("click");
Here is the updated codepen
Be aware of one thing - .off('click') removes all event listeners of type click from the element. If you want remove just this function, assign the function to a variable and then use the variable in the on and off calls. Like below:
event_fce = function(event) {
//do stuff here
$(this).off('click', event_fce);
}
$('li').on('click', event_fce);
You could turn off click as soon as one option is selected (right/wrong), like below:
Codepen updated
$(this).siblings().off("click"); //add this to where appropriate, such as either in `if` or `else` or both.

How can I get one button to reveal different hidden divs with each click?

With jQuery (or javascript), how can I have one button reveal different hidden (display: none) divs with each click? For example, on the first click of the button, div1 should appear. On the second click of the same button, div2 will appear also (so both div1 and div2 are visible). Same for div3, etc.
With the code I have now, the first button click reveals all the hidden divs at once. Here's an example:
$(document).ready(function () {
$('button').click(function () {
$('.div1').show('slow');
});
$('button').click(function () {
$('.div2').show('slow');
});
$('button').click(function () {
$('.div3').show('slow');
});
});
The reason they are all appearing at once is because what you have done now is appended three separate click handlers to the same object that each show in a separate div. Now every time you click on "button", all three of those functions are going to run.
What you could do is collect all the divs you want to show in one object, and keep a count of the amount of divs you have already shown in.
var count = 0,
$allDivs = $('.div1, .div2, .div3');
$('.button').click( function() {
if( count < $allDivs.length - 1 ) {
$allDivs.eq( count ).show( 'slow' );
count++;
}
});
If you select all the divs at once, then you can use jQuery's eq() method to pick them out one at a time.
Here is a working example on JS fiddle: http://jsfiddle.net/grammar/76arV/
Hope this helps!
var blocks = $('.div1, .div2, .div3');
$('button').click(function () {
if (block = blocks.next())
block.show('slow');
});
What about this?
var iShow = 0;
$('button').click(function () {
$('.show:eq(' + iShow + ')').show('slow');
iShow = iShow + 1;
});
So in this example i gave every element that you want to interact with the button the class .show. This way you can just select any of these element by the index value, you do this with .eq().
First .show element has the index value of 0, so that is where we start(our default value).
Each time we click we increasing the variable by one so next there is clicked, the next element will be showed.
Based on what you want to do next, you can do the same with hiding all the elements again one by one.
Hope this helped you.
jsFiddle

Show only one element and hide others without toggle

I've been researching this and many of the answers involve toggle function. The problem is I want one elements to be shown at all time, which isn't possible if toggle is used (they may accidently click something and it disappears). So I was doing it this way:
$(document).ready(function(){
$("#goals").hide();
$("#History").addClass("selected");
$("#History").click(function(e){
e.preventDefault();
$("#history").show();
$("#goals").hide();
$("#History").addClass("selected");
$("#Goals").removeClass("selected");
});
$("#Goals").click(function(e){
e.preventDefault();
$("#goals").show();
$("#history").hide();
$("#Goals").addClass("selected");
$("#History").removeClass("selected");
});
});
Except it's prob too tedious and I'm sure there's a better way. I'm trying to find solutions that use hide and show only or if the requirement can be fulfilled. Any help is appreciated...I'm not advanced at jQuery yet so please provide explanation. Thank you
You can give them a class.. or just combine the them in one selector
$(document).ready(function(){
$("#goals").hide();
$("#History").addClass("selected");
var eles = $("#History,#Goals");
eles.click(function(e){
e.preventDefault();
$(this).show().addClass('selected'); // show and add class to current clicked
eles.not(this).hide().removeClass('selected'); // hide and remove class for the other one
});
});
EDIT: I didn't notice you actually had different id's
var hg = $("#history,#goals");
var HG = $("#History,#Goals");
HG.click(function(e){
e.preventDefault();
var el = $('#'+this.id.toLowerCase());
el.show();
hg.not(el).hide();
$(this).addClass("selected");
HG.not(this).removeClass("selected");
});

Categories

Resources