Select last element on page with specific class - javascript

I am working on a quizz test. I want to select the last element on the page with a specific class so that when the user clicks on it the result of the quizz appears. Right now I'm doing it by adding an extra class but I wanted to know if there's a way of traversing the document without the use of classes so that no matter how many questions are added to the quizz the function will be triggered when the last element is clicked. I tried the solutions suggested here and here but it doesn't seem to work. Thanks
I created the following codepen for it
//get total of questions
var $questionNumber = $('h2').length;
console.log($questionNumber);
//caching final score
var $totalScore=0;
$('li').click(function(){
//caching variables
var $parent = $(this).parent();
var $span = $(this).find('.fa');
//deactivate options on click
$parent.find('li').off("click");
//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 answer
var $answerReveal= $parent.next('.answerReveal').show();
var $toShowCorrect = $answerReveal.find('.quizzAnswerC');
var $toShowFalse = $answerReveal.find('.quizzAnswerF');
$toShowCorrect.show();
$toShowFalse.remove();
//add 1 to total score
$totalScore+=1;
//console.log($totalScore);
}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 highlight
$parent.find('.correct').addClass('correctAnswer');
};
});//end click function
//print Results
function printResult(){
var resultText = '<p>';
if ($totalScore === $questionNumber){
resultText+='You got '+ $totalScore+ ' out of '+$questionNumber+'! </p>';
$('.resultContainer').append(resultText);
$('#halfText').append('<p>This is awesome!</p>');
$('#halfImage').append('<img src="http://placehold.it/350x150" width="100%"><img>');
}else if($totalScore>=3 && $totalScore < $questionNumber){
resultText+='You got '+ $totalScore+ ' out of '+$questionNumber+'! </p>';
$('.resultContainer').append(resultText);
$('#halfText').append('<p>So and so...better luck next time</p>');
$('#halfImage').append('<img src="http://placehold.it/350x150" width="100%"><img>');
}else if ($totalScore<3){
resultText+='You got '+ $totalScore+ ' out of '+$questionNumber+' </p>';
$('.resultContainer').append(resultText);
$('#halfText').append('<p>No..no...no...you have to try harder</p>');
$('#halfImage').append('<img src="http://placehold.it/350x150" width="100%"><img>');
}
};//end function
//final score
$('li.last').click(function(){
//show result after last li is clicked
var $height = $('.finalResult').height();
printResult();
console.log($totalScore)
$('.finalResult').show();
$('html, body').animate({
scrollTop: $(document).height()-$height},
1400);
});

Getting the last element with a given class is very straightforward with jQuery:
$('selector').last().click(...);

you can select last element with class using:
$( ".classname:last-child" ).click(function(){});

Related

Moving and changing element id's using jquery and ajax

I am working on a project to move div elements around and update their id.
It calls the script and passes the tag's id number. So far it completely works that far. It moves the element up one place and swaps the div id numbers. The only thing is that when I click on the same div to move it again (like moving div#3 to spot#1 by clicking "up" a second time), It doesn't respond to the new div "id" even though it appears to be successfully changed when i inspect it in the browser.
The javascript: just showing the if up
enter code here
$("#content_update").on("click", ".rowupdown", function(){
// button is up or down
var upordown = $(this).attr('value');
// id number of div from button
var number = $(this).attr('id');
// current div can edit id
var $moveid = $("div#row" + number);
var numberint = parseInt(number);
if (upordown == "up") {
var s = numberint - 1;
//number of div to place before and to set id with
var numberstring = s.toString();
//***ability to select the other div element***
var $diffrow = "div#row" + numberstring;
//** update current div id***
var $editcurrent = "div#row" + number;
// puts other div id into this one
var newid = "row" + numberstring;
// puts in this id to the other div
var editother = "row" + number;
$($diffrow).before($moveid); // finally moves the current div up one
$($diffrow).attr("id", editother);
$($editcurrent).attr("id", newid); //changes id of current div to one before
}
});
the HTML (i have a button that adds new divs and adds 1 to give them a unique id, first click=1 second makes div id = 2 and so on, it doesn't have to do with the question though.)
case "row":
if (!isset($_SESSION["rownumber"])){
$row = $_SESSION["rownumber"] = 1;
}
$row = $_SESSION["rownumber"]++;
echo " the html
<div class='panel panel-default' id='row".$row."'>
<button class='rowupdown point' id='".$row."' value='up'>up</button>
</div>

Change div id attribute on click

I have two divs. When I click on a button it moves to another div
Here is it looks like
I realize it like this
var counter = 0;
$('.click2').on('click', function () {
counter++;
if (counter > 10) {
return false;
}
else {
var elem = $(this).closest('.title');
$('.title2').append($(elem).html()).show();
}
});
But I have one problem I need to change Id of elements when it moves
I know that is realizing like this
$(this).attr('id', '.title_left');
But I can have 1-10 divs in left column and need to name it .title_left1. Next will be title_left2 and ++
How I can code it?
You can just append counter to the id attribute:
$(this).attr('id', '.title_left' + counter);

jQuery: HIde prev and next div after a click event

My goal is to hide the prev or next div after clicking on a li element.
This is the script:
jQuery('.menu-ul li').on('click',function(){
var current_id = jQuery(this).data('id');
var menu_id = '#' + current_id;
jQuery(menu_id).next("div").attr("id").hide()
jQuery(menu_id).prev("div").attr("id").hide();
});
The script above works fine, but when I put the function hide() I get this error:
Uncaught TypeError: jQuery(...).next(...).attr(...).hide is not a function
How can I solve it?
To ge the previous element use $(selector).prev(), and to get the next use $(selector).next(). Then use .hide() to hide any, or both of them.
Like this:
jQuery('.menu-ul li').on('click',function(){
var current_id = jQuery(this).data('id');
// We get the element and store it, so we don't get it twice later.
var element = jQuery('#' + current_id);
element.prev().hide();
element.next().hide();
});
try following code,
jQuery('.menu-ul li').on('click',function(){
var current_id = jQuery(this).data('id');
var menu_id = '#' + current_id;
jQuery(menu_id).next("div").hide()
jQuery(menu_id).prev("div").hide();
});

How to show/hide certain number of divs using a single button?

I have elements that should show or hide after the first five elements. When I click on 'Load More...' with an id #loadMore, it will trigger to show all the elements and change the div id to #showLess to execute a different set of action. So, when I click #showLess to hide the rest of the thumbnails, nothing happens. The $('#showLess').click(function() isn't executing but instead executes the $('#loadMore').click(function() again.
Here's a jsfiddle.
jQuery:
var vidThumbnail = "";
var elements = $('.section.thumbnail .thumb > .video-thumbnail');
for (i = 0; i < 25; i++) // loop thru 25 thumbnails
{
vidThumbnail = '<div class="video-thumbnail">child ' + i + '</div>';
$('.section.thumbnail .thumb').append(vidThumbnail);
if(i > 5) // when it reaches the first five thumbnails, hide the rest
$('.section.thumbnail .thumb .video-thumbnail').eq(i).hide();
}
$('#loadMore').click(function() // show them all
{
$('.section.thumbnail .thumb .video-thumbnail').show();
$(this).attr('id', 'showLess'); // change id to show less
$(this).text('Show Less...'); // change text value
});
$('#showLess').click(function()
{
// slice the first five, hide the rest
$(elements).slice(5).each(function(i)
{
$('.section.thumbnail .thumb .video-thumbnail').eq(i).hide();
});
$(this).attr('id', 'loadMore'); // change id to show less
$(this).text('Load More...'); // change text value
});
I've fixed a bit your code because you do some mistakes.
Look here: https://jsfiddle.net/sbz51wdz/36/
I explain your error:
When you define a click action, jQuery add an event on a matched DOM elements. If you simply change the id attribute and attach another event of that new ID before the action of changing ID was started, jQuery will not find anything with the new ID. My favourite solution is add the click event on single element with a fixed class or id. Inside the function, everytime, check if the element has or not a class, and then do the right action. Just use somenthing like $(this).hasClass(...)
After this, is better to define single function called when it needs.
Last but not least, it's important to attach assignments after the context is defined in the DOM. so var elements = $('.section.thumbnail .thumb > .video-thumbnail'); this have to be written after the foreach cycle that generate the elements.
Hope its help! :)
You are changing the id of the div on click so should use $(document) and bind all ids with that like
$(document).on('click', '#loadMore', function()
https://jsfiddle.net/sbz51wdz/35/
I have created a div class name "test" and put the loadMore div inside it for binding. You need it cause a hidden or invisible div need to bind in every event occurrence in jquery. then i modified the jquery code in this below way and it works.
var vidThumbnail = "";
var elements = $('.section.thumbnail .thumb > .video-thumbnail');
for (i = 0; i < 25; i++) // loop thru 25 thumbnails
{
vidThumbnail = '<div class="video-thumbnail">child ' + i + '</div>';
$('.section.thumbnail .thumb').append(vidThumbnail);
if(i > 5) // when it reaches the first five thumbnails, hide the rest
$('.section.thumbnail .thumb .video-thumbnail').eq(i).hide();
}
$('.test').on('click', '#loadMore', function() // show them all
{
$('.section.thumbnail .thumb .video-thumbnail').show();
$(this).attr('id', 'showLess'); // change id to show less
$(this).text('Show Less...'); // change text value
});
$('.test').on('click', '#showLess', function()
{
// slice the first five, hide the rest
var j = 6;
$('.section.thumbnail .thumb .video-thumbnail').each(function(i)
{
$('.section.thumbnail .thumb .video-thumbnail').eq(j).hide();
j++;
});
$(this).attr('id', 'loadMore'); // change id to show less
$(this).text('Load More...'); // change text value
});

Increase element ID by one after every click?

I am trying to clone multiple divs on my page by using the jQuery .clone() method. The problem is, as soon as a div is cloned, it needs to have a unique ID. The cloned ID has to be there too. I was thinking I could keep the old ID and then just add a number on, increasing as more div's are on the page.
Example: base ID = one, so div one would be id, then div two would be id-2, then div three would be id-3, etc.
Is this possible? My attempt at this is below:
$("a").click(function(){
var target = $(this).attr("href");
var id = $(target).attr("id");
$(target).clone().attr("id",id + $(id).size()).attr("class","drag").appendTo("body");
});
Each a tag looks like this:
One
Two
Then the cloned element looks like this:
<div class="drag base" style="background-color:blue" id="one"></div>
<div class="drag base" style="background-color:green" id="two"></div>
See this: http://jsfiddle.net/3tu7V/1/
$(function(){
$("a").click(function(){
var target = $(this).attr("href");
var id = $(target).attr("id");
var click = $(target).data("clicked") || 0;
$(target).data("clicked", ++click);
$(target).clone().attr("id",id + click).attr("class","drag").appendTo("body");
});
});
​
I think this does what you want according to your comment:
"Ah, is there any way for the element ID to be reset when the base ID is unique? Ex.) "If you clone div "one", it will produce "one-1", then "one-2", but if you then clone div "two", it will produce "two-3", not "two-1""
i think in ur case $(id).size() will always be = 2. (only the last one and its clone will have the same id)
why don't you use a global variable var clickNumber that you increment each time.
your code will be
var clickNumber = 0;
$("a").click(function(){
var target = $(this).attr("href");
var id = $(target).attr("id");
clickNumber ++;
$(target).clone().attr("id","id-" + clickNumber).attr("class","drag").appendTo("body");
});
See this live example
var increment = 2;
$('a').live('click', function() {
$(this).clone().attr('id','id-' + (increment++)).appendTo('body');
});​
Result:
Revised answer:
You can use the jQuery attribute starts with selector to keep a track of the clones, and their counts:
$("a").click(function() {
var targetId = $(this).attr("href").substring(1); // "one", "two"
var count = $("div[id^=" + targetId + "]").length; // initial value will be 1
$("#" + targetId).clone().attr("id", targetId + '-' + count).attr("class", "drag").appendTo("body");
});
Demo
You could do something like this:
$('a').addClass('link');
$('body').on('click', 'a', function() {
$(this).clone(true).attr('id', 'id-' + $('.link').length).appendTo('body');
});​
Demo: http://jsfiddle.net/Em8PE/1/

Categories