I am new to jQuery, i want to get the list of last div ID's minimum last three iD's.
my need is when user clicks on cancel button then i want to move user to last 2nd clicked div.
Try this:
var clicks = [];
$("div[id^=test]").on('click',function() {
clicks.push(this.id);
});
$("button").on('click',function() {
console.log(clicks.pop())
});
This uses a array to store all the clicks and the show & removes the last one on button click.
To read about .push() and .pop().
Demo here
Make an "history" array that push the id everytime the div is clicked :
var history = [];
$('div').click(function(){
history.unshift(this.id);
})
And on cancel click:
$('button.cancel').click(function(){
history.shift();
})
To save previous clicks you'll want to store clicks in an array as follows:
clicks = [];
$(function () {
$("div").on("click", function (e) {
// The following is what you wanted, but the uncommented code is better (as it saves future DOM lookups)
// clicks.shift($(this).attr("id"));
clicks.shift(this);
// If you want to use jQuery on the objects, you'll need to call jQuery on them ex: $(this)
// If you do want to remove previous elements, uncomment the following code
// if(clicks.length > 3){
// clicks.pop();
// }
});
});
Each time a click occurs, the object that was clicked on will be stored in the array (clicks.push(this)). Later you can reference the array. clicks[0] will have the most recent click, clicks[1] the next most recent, and so on.
So, to do what you described, you would make a function along the lines of:
$(function () {
$("#cancel").on("click", function (e) {
$(clicks[1]).yourMethods();
});
});
Related
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.
I am using $(this) to get the current selected(clicked) element of a specific class .For the first time its coming fine i.e i am getting the selected element but as soon as i click on second time it is giving the alert of the old as well as new selection .I am not able to find out what is the issue..
Here is the code..
$('.l-one').click(function () {
var tableName = $(this).text();
//Table Name Lable
$("#lbl").text(tableName);
//Panel
$("#Perticulars").show();
$('.my-new-three').click(function () {
var dishvalue = $(this).text(); //get the value of dish item and display in the table
//console.log(dishvalue);
alert(tableName);
alert(dishvalue);
if (localStorage.getItem(tableName) != null) {
alert("b");
In the alert(tableName); i am getting alert of all the tables selected previously .Please help me to resolve this..
Thanks...
use below code . only click assign events to each time when you click '.l-one'. so if you click '.l-one' 3 time 'click' event assign 3 time to '.my-new-three'.
unbind() function remove event from element and bind() function attach event to element. so here as per your code each time when you click '.l-one' unbind remove click event from '.my-new-three' and bind function again assign click event to '.my-new-three'.
$('.my-new-three').unbind('click').bind('click',function () {});
other way is to use separate click event methods.
$('.l-one').on('click', function () { });
$('.my-new-three').on('click',function () {})
Use separate click handler instead of using click handler insider another one. Consider this code:
$('.l-one').click(function () {
//code
}
$('.my-new-three').on("click",function () {
//code
}
Assuming If .my-new-three exists inside .l-one or .my-new-three creating dynamically then use this:
$('.l-one').on("click",".my-new-three",function () {
//code
}
I've got a table with different columns identified with different classes.
I've also a checkbox binded to every column.
I created a function which is called on the click of any checkbox. In this function I hide/show the column which is linked to this.
It doesn't have any javascript error, and the code is the following:
$(document).ready(function(){
$('ul input').click(function(){
//alert('yooo');
if ($(this).is(':checked')) {
//alert('checked');
$("td."+replaceAll(" ","_",$(this).val())).show();
$("th."+replaceAll(" ","_",$(this).val())).show();
//alert($("td").length);
}
else{
//alert('unselected');
$("td."+replaceAll(" ","_",$(this).val())).hide();
$("th."+replaceAll(" ","_",$(this).val())).hide();
}
});
});
However, after every click, the action has a lag (after many clicks it becomes tooooooo slow, many seconds).
I tried also with .css instead of hide-show, but it doesn't make any change.
I understood that the problem was linked only to checkbox, not on callback or on jquery function. I solved the problem simply by working with radio input, adding a "true" and a "false" radio input for every checkbox that was in the page.
Instead of running the jQuery selector on every click like below:
$("td."+replaceAll(" ","_",$(this).val()))
You could set up some sort of caching like:
var cache = {} //<-- declare this outside your click handler
//add the code below inside your click handler
className = replaceAll(" ","_",$(this).val())
if(!cache[className])
cache[className ] = $("td."+className + ", th."+className); //select all the elements once and store in the cache object
$el = cache[className];
if ($(this).is(':checked'))
$el.show();
else
$el.hide();
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
I've written some javascript using jQuery to replace any select lists with a div and ul alternative so that it will give me some more styling control and make the drop downs look the same cross browser. The below code works 99% for me but I have one issue. At the bottom of the code I have had to use .delay() to tell the code in a way to wait for the .each() loop above to finish doing what its doing. The problem with this is that there is atleast one second untill the replacement happens leaving a flash of the old select boxes. Also I can forsee another problem is what if it takes more than one second for the each() loop to complete...
How can I get the code at the bottom to only run once the each loop has run and complete. Also I welcome any optimizations on the rest of the code.
EDIT: Some of the HTML has been stripped from the code so I have pastebinned it: http://pastebin.com/4HFLjHE1
// Check when ready
$(function() {
// Find dropdowns
$("select.dropdownreplace").each(function() {replaceDropDown(this);});
// If document clicked anywhere hide drop downs
$(document).click(function(event){
$("div.dropdownreplace ul").hide();
});
});
function replaceDropDown(that) {
// Create HTML for new drop down
// hidden field
var hiddeninput = $('');
// div
var dropdowndiv = $(''+$(":selected", that).text()+'');
// loop through values and make li's
$("option", that).each(function() {
$("ul", dropdowndiv).append(''+$(this).val()+''+$(this).text()+'');
// set click handler for this drop down
$(dropdowndiv).click(function() {
$("ul", this).show();
return false;
});
// set click handler for link items
$("a", dropdowndiv).click(function() {
// Get name of hidden input
var nameofdropdown = $(this).parent().parent().parent().attr('id');
var nameofinput = nameofdropdown.replace("dropdownreplacement_", "");
// set hidden input value to whats been clicked
$("[name='"+nameofinput+"']").val($(this).parent().find("span").text());
// set div
$("div#"+nameofdropdown+" > span").text($(this).text());
$("div#"+nameofdropdown+" ul").hide();
return false;
});
});
// Remove drop down then add in replacement html
$(that).delay(1000).after(hiddeninput);
$(that).delay(1100).after(dropdowndiv);
$(that).delay(1200).remove();
}
Thnaks
Scott
Inside your function, compare the index jquery passes you, with the total number of items you have.
I don't know your html, but I believe you can do this.
Change your function so it receives the index param that jquery sends.
$("option", that).each(function(index) {
Then, at the end of that function compare the length with the index, if they are the same, then you're done
if ( $('option', that).length == (index +1 ) ) {
$(that).after(hiddeninput);
$(that).after(dropdowndiv);
$(that).remove();
}
From my tests, this should be what you need. Don't know if there is a more "standard" way to do it.
Hope this helps
What you have to do is create a callback functionl. In your each(), after the initial function you can indicate it has to do some more things when it's finished:
$("option", that).each(function() {
<...code...>
}, function() {
<...code...> //this gets performed after the previous function is complete
});