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

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
});

Related

Opacity on first and last element of slider which has ".active" classes using javascript or css

I have owl carousel slider with 5 items. And my problem is that i need first and last element of my slider to be always with opacity. Slider has like 15 elements which 9 cloned, 5 have .active class and one with cloned and .active.
I tryied make it using javascript where i found all ".active" classes in slider, but i don't exactly know what i should do with object which was found.
There is code which found all ".active" classes
var owlCarouselActive = document.getElementById("slider-tour").getElementsByClassName("owl-item active");
I need in order to this .active first and last have :before with my background style when i click on button prev or next.
You could do this with javascript
var owlCarouselActive = document.getElementsByClassName("owl-item active");
var first = owlCarouselActive[0]; //get first item
var last = owlCarouselActive[owlCarouselActive.length - 1]; //get last item
first.style.opacity = 0.8;
last.style.opacity = 0.8;
I'm not at home but try something like this:
function setOpacity() {
var elements = $('.active');
let count = 0;
$(elements).each(function(k,v) {
if (count == 0 || count == elements.length - 1) {
$(v).css('opacity', '0.8');
}
count++;
});
}
$(document).ready(function() {
setOpacity();
});
Run that function everytime you want it to update.
E.G on a button click.
You can use owlCarouselActive [0] to access the first element and owlCarouselActive [owlCarouselActive.length-1] to access the last element. Generally you can access i-th element by owlCarouselActive [i].

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);

Select last element on page with specific class

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(){});

Append HTML but have separate fadeIn on document click

I am appending a div every time the user clicks anywhere on the page. I want the div's to fadeIn but the way I first did this each div that was appended had the same ID. This is a problem if I want each letter div to fadeIn separately. So I tried to use a count to make each div I append have a separate name but this hasn't work. Each time a new div is appended all appended divs fadeIn not just the one just recently added. How might I change this?
var count = 0;
if(firstLetter != "") {
count++;
//Create a new circle letter by inserting new div class
$("p").append('<div class="circle' + count +'" style="border-radius: 50%;width: 36px;height:36px;padding:8px;background:#FF7D5C;color:black;text-align:center;font:32px Arial, sans-serif;display:inline-block;margin-right:4px;margin-bottom:4px;">' + firstLetter.toUpperCase() + '</div>').hide().fadeIn('slow');
}
Many Thanks :)
Try this. In your code all the divs play the effect because the element returned by all the functions that you're calling is the < p > element.
$("p").append('<div class="circle' + count +'" style="border-radius: 50%;width: 36px;height:36px;padding:8px;background:#FF7D5C;color:black;text-align:center;font:32px Arial, sans-serif;display:inline-block;margin-right:4px;margin-bottom:4px;">' + firstLetter.toUpperCase() + '</div>');
$("p").children().last().hide().fadeIn();
OR a simpler way
$("p div:last").hide().fadeIn();

JavaScript multiple draggable DIV windows, zIndex on focus

I have multiple JavaScript draggable DIV windows. When clicking a DIV, I want the window to get the highest z-index value. I've made a solution by adding/removing classes to the element in focus, BUT, I would like the windows to keep their "layer" -order (as if the entire DIV window node was re-appended to the DOM when being clicked).
Let's say there are five DIV's in the DOM. div1, div2, div3, div4 and div5. -div5 is closest to the front and div1 is in the back and so on.
When clicking div1, -div1 will get focus and put to front, setting div5 back one step. Then clicking div3, -div3 gets closest to front and div1 and div5 are put back one step like this: div2, div4, div5, div1, div3.
If you don't want to loop through all your divs and don't want to mess up with z-index you can just append again that div to the parent element (the body?) before dragging.
function stepUpNode(elementDragged){
var parentNode = elementDragged.parentNode;
parentNode.appendChild(elementDragged);
}
If you'd like to do this without re-appending the element, my solution when I wrote something similar a while back was to keep track of the maximum z-index. Every time a window is brought forward, the maximum z-index is incremented and the element's z-index is set to the new value. Of course, if someone messes with the windows enough, they might end up having very large z-index values, so this isn't always the best solution.
var maximumZIndex = 1;
var bringForward = function (element) {
maximumZIndex += 1;
element.style.zIndex = maximumZIndex;
}
The first and most likely easiest approach: simply increase the maximum z-index every time a div gets selected. Since the z-index value can become pretty large (2147483647 if I remember correctly) you most likely will never run out of levels...
The following snippets use some jQuery:
var frontmostWindow = null;
var topZIndex = 10;
$('div').click(function() {
if (this != frontmostWindow) {
frontmostWindow = this;
topZIndex++;
$(this).css('zLevel', topZIndex);
// anything else needed to acticate your div
// ...
}
});
If you have restrictions on the z-indices you can use, you will need to re-assign levels every time a different div gets selected, e.g. like this:
// store z-index-ordered divs in an array
var divs = $('div').toArray().sort(function(a, b) {
return parseInt($(a).css('zIndex'), 10) - parseInt($(b).css('zIndex'), 10);
});
// store available z-indices
var zIndices = [];
for (var i = 0; i < divs.length; ++i) {
zIndices.push($(divs[i]).css('zIndex'));
}
// Event listener for clicks
$('div').click(function() {
alert("heyya " + this.id);
var element = this;
var index = divs.indexOf(element);
// check if clicked element is not already the frontmost
if (index < divs.length - 1) {
// remove div from array and insert again at end
divs.splice(index, 1);
divs.push(this);
// re-assign stored z-indices for new div order
for (var i = 0; i < divs.length; ++i) {
$(divs[i]).css('zIndex', zIndices[i]);
}
// anything else needed to acticate your div
// ...
}
});

Categories