How to save the last hovered state on an HTML element? - javascript

I am working on a Wordpress shortcode for generating dynamically circles.
At my current version I have a problem with saving my current and my last hover state.
Here is a fiddle
I have a problem displaying the text under the circles. The text should be displayed from the last hovered circle until I hover over a new one.
Is there maybe a better solution to my problem?
I think my problem is in the hover end.
[...] ,function () {
$contentBoxPrevious = $contentBoxCurrent;
$contentBoxCurrent.removeClass('active-text');
$(this).removeClass('hover active');
}

Move this line
$contentBoxPrevious.removeClass('active-text');
from the handleOut function to the middle of handleIn function like this https://jsfiddle.net/eu0jcmh0/
What you were doing wrong was that you were removing the "active-text" class every time you moused out of the element instead of removed it when you moused on another element, hope I helped!

Your code looked way too complicated...
So I just rewrote it my way to achieve what I think you want as a result.
Here's the code:
$(document).ready(function() {
// Set all texts invisible
$(".text-content").css({
"opacity": 0
});
// Declare previous and active indexes vars
var previous_index;
var active_index;
$(".icon-circle").hover(function() {
// On mouseenter, getting this index.
active_index = $(this).data("index");
// Show associated text.
$(this).parent().find(".text-content").css({
"opacity": 1
});
// Hide previous associated text.
if (active_index != previous_index) {
$("[data-index='" + previous_index + "']").parent().find(".text-content").css({
"opacity": 0
});
}
}, function() {
// On mouseout, just keeping previous index...
previous_index = active_index;
});
});
Working Fiddle.

Related

Cycle through classes on Jquery to animate

enter image description here
I'm trying to create an animation where if you click the button the circles animate around the path and changes size. I'm not sure how i would cycle the classes on the next click ?
http://bluemoontesting.co.uk/bluemoon2016/people.html
I'm using an svg and have targeted the elements with this so far:
<script>
$(".animate-slider").click(function() {
$('.st7').toggleClass("top-left");
$('#XMLID_292_').toggleClass("left");
$('#XMLID_293_').toggleClass("center-right");
$('#XMLID_297_').toggleClass("top-right");
$('#XMLID_301_').toggleClass("top");
$('#XMLID_283_').toggleClass("top-center");
});
</script>
If anyone could help me i'd be very grateful :)
Thanks
I would take a little different approach. Instead of toggling classes, to get it to move to more than two positions, you will need to cycle the classes assigned to each element instead. Storing the class names in an array would allow you to move them in the array to cycle the position that each element moves to next. I created a simplified example.
$(document).ready(function () {
var steps = ['right', 'bottom-right', 'bottom-left', 'left', 'top'],
allClasses = steps.join(' ');
$('#go').click(function() {
$('#a').removeClass(allClasses).addClass(steps[0]);
$('#b').removeClass(allClasses).addClass(steps[1]);
$('#c').removeClass(allClasses).addClass(steps[2]);
$('#d').removeClass(allClasses).addClass(steps[3]);
$('#e').removeClass(allClasses).addClass(steps[4]);
steps.push(steps.shift()); // move first element to the end
// to cycle in the other direction you would pop and unshift instead
// steps.unshift(steps.pop()); // move last element to the beginning
});
});
You could just use setInterval like so:
var $st7 = $('.st7'); //class selectors can be expensive, so cache them
function rotate() {
$st7.toggleClass("top-left");
$('#XMLID_292_').toggleClass("left");
$('#XMLID_293_').toggleClass("center-right");
$('#XMLID_297_').toggleClass("top-right");
$('#XMLID_301_').toggleClass("top");
$('#XMLID_283_').toggleClass("top-center");
}
//2000 is milliseconds, so that's two seconds
var rotateIntervalId = setInterval(rotate, 2000);
//optionally consider stopping/starting the effect on mouse hover/exit
$('#Layer_1').on('hover', function() {
clearInterval(rotateIntervalId);
}).on('blur', function() {
rotateIntervalId = setInterval(rotate, 2000);
});

Adding and removing a class at the same time as updating a div

I am very new to JavaScript. I am trying to update a div, which works fine before the add and remove class pieces are added. The problem is when I add the class I can't seem to get it to be removed when the when the next image is clicked. I have used a remove class option, but it doesn't seem to want to work.
Any help is appreciated. Here is the code:
$('[class^="question"]').on('click', function(e) {
e.preventDefault();
var numb = this.className.replace('question', '');
$('[id^="answer"]').hide();
$('.question*').removeClass('question*selected');
$('#answer' + numb).show();
$('.question' + numb).addClass('question' + numb + 'selected');
});
Here is a link to the Fiddle I am Playing with.
Thanks.
You can keep track of your added class by defining a global variable. I created a working example in CODEPEN.
$(document).ready(function() {
var appliedClass = "container1";
var classNo = 1;
$(".buttonCon").click(function() {
if ($(".container").hasClass(appliedClass)) {
$(".container").removeClass(appliedClass);
classNo++;
if (classNo > 4) {classNo = 1;}
appliedClass = "container" + classNo;
$(".container").addClass(appliedClass);
}
});
});
I have appliedClass variable which keeps tracking of the latest added class. Every time you click on the button with .buttonCon class, this variable will be updated to the new added class. Next time, first we remove the former class. Then we added the new one. The second if statement might not be needed in your case, but in my example, I needed it to keep looping through container1 to container4 classes.
You've set yourself up with a really difficult-to-work-with class structure -- this can be a lot easier than you're making it. Give each of your "question" links the class 'question' and the unique id "question1", "question2", etc. Same for the answer nodes: class "answer" and id "answer1", "answer2" etc.
Now you can easily access all question links with $('.question') or all answers with $('.answer'), and can use the IDs to identify individual nodes as needed:
$('.question').on('click', function(e) {
e.preventDefault();
var numb = this.id.replace('question', '');
var answerNode = $('#answer'+numb);
if (answerNode.hasClass('hide')) {
// the Q they clicked on is not yet visible
$('.answer').addClass('hide'); // hide all answers
answerNode.removeClass('hide'); // show the desired one
} else {
// the Q they clicked on is already visible, so toggle it back off
answerNode.addClass('hide');
}
});
http://jsfiddle.net/647dadtj/

jQuery: Only substract 1 after adding 1

How can I do this in jQuery. I already have a script that can add 1 after clicking a button. But I also want something that should substract 1 if I click on the button again, and return the button to its original state.
Here's my current jquery code
$(document).ready(function() {
$("#addMe").one('click',function(){
var counter = parseInt($("#hiddenVal").val());
counter++;
$("#hiddenVal").val(counter);
$("#theCount").text(counter);
$("#addMe").toggleClass('active');
});
});
Here's my live js fiddle: http://jsfiddle.net/jehzlau/7hv2eyv0/
Right now, it adds 1 after I click it. The button should only be clickable once to add + 1. And the color of the button will change. That's the first one that I'm trying to achieve, and it's already working.
The only problem I have now is to revert the changes after clicking it again.
For example, if you click on the button, it's now blue and the heart is black, and the number is 2. What I want is if you click it again, the button will become green again by default, the heart to white, and the number 2 to 1. I just want to reverse what happened in the second click. Then if I click on it again (3rd click), it will go back to 2, then the button will be blue, and the heart will be black again. And if I click on it again (4th click), it will revert again. And so on... and so forth...
That's all I want to do, but I can't do it. I hope someone here can point me to the right direction. :(
I would do it this way. See if active class exist and then increment/decrement counter based on it:
$("#addMe").on('click',function(){
var counter = parseInt($("#hiddenVal").val());
if($(this).hasClass('active'))
counter--;
else
counter++;
$("#hiddenVal").val(counter);
$("#theCount").text(counter);
$("#addMe").toggleClass('active');
});
Working Demo
Try to use on() not one() like,
$(document).ready(function () {
$("#addMe").on('click', function () { // use on instead of one
var counter = parseInt($("#hiddenVal").val());
$(this).hasClass('active') ? 1 : 2;// toggle text 1,2
$("#hiddenVal").val(counter);
$("#theCount").text(counter);
$("#addMe").toggleClass('active');
});
});
Live Demo
If you want to add 1 and subtract 1 from any hiddenVal then, you can change it like,
$(document).ready(function () {
$("#addMe").on('click', function () { // use on instead of one
var counter = parseInt($("#hiddenVal").val());
// change the line where counter initialization takes place like
$(this).hasClass('active') ? counter-- : counter++ ;
$("#hiddenVal").val(counter);
$("#theCount").text(counter);
$("#addMe").toggleClass('active');
});
});
If you do not really want to count but just toggle, use a global variable and just toggle:
var counter = false;
$(document).ready(function() {
$("#addMe").click(function(){
counter = !counter;
$("#hiddenVal").val(counter);
$("#theCount").text(counter);
$("#addMe").toggleClass('active');
});
});
You can also drop the hidden element in your form.

containing div does not resize correctly

On this page, 3 reviews are displayed in a Bootstrap carousel. As you paginate through the reviews, the <div> with the grey background should resize to fit the length of the review. This works reasonably well until you wrap around the end of the review list.
For example, if you use the next button to go forwards through the reviews, then when you go from the last review (#3) to to the first review, a big empty space is left under the first review. Similarly if you use the prev button to go backwards through the reviews, then when you go from the first review to the last (#3), the text of the review overflows the containing div (see screenshot below).
In summary, whenever you wrap around the list of reviews, either by using the prev button to go from #1 to #3 or the next button to go from #3 to #1) the containing div is not correctly resized.
The event handlers that are called when the user paginates through this carousel are at the bottom of the page (reproduced here for convenience):
$(document).ready(function () {
$('#reviewsCarousel').carousel({
interval:null
});
// reviewsCarousel height animation and review counter (set .reviewCount to
// the amount of .item in #reviewsCarousel, on .nextReview or .prevReview button
// clicks: set the carousel-inner class to the animate to the height of the next
// item or the first item if there is no next item, on carousel slide, set the
// reviewIndex class text to the index position of the .active .item)
$("#reviewsCarousel .reviewCount").html($('#reviewsCarousel .item').length);
$("#reviewsCarousel .btn.nextReview").click(function () {
var reviewHeight = $("#reviewsCarousel .item.active").next(".item").height();
if (reviewHeight === undefined) {
var reviewHeight = $("#reviewsCarousel .item").first(".item").height();
}
$("#reviewsCarousel .carousel-inner").animate({"height":reviewHeight + "px"}, 400);
$('#reviewsCarousel').bind('slid', function () {
$("#reviewsCarousel .reviewIndex").html($("#reviewsCarousel .active").index("#reviewsCarousel .item") + 1);
});
});
$("#reviewsCarousel .btn.prevReview").click(function () {
var reviewHeight = $("#reviewsCarousel .item.active").prev(".item").height();
if (reviewHeight === undefined) {
var reviewHeight = $("#reviewsCarousel .item").last(".item").height();
}
$("#reviewsCarousel .carousel-inner").animate({"height":reviewHeight + "px"}, 400);
$('#reviewsCarousel').bind('slid', function () {
$("#reviewsCarousel .reviewIndex").html($("#reviewsCarousel .active").index("#reviewsCarousel .item") + 1);
});
});
});
Here are a couple of screenshots showing the problem:
I tried a little something in the console:
$("#reviewsCarousel .item.active").next(".item").height();
And found out it was null.
if (reviewHeight === undefined) // It's never this.
You never get in the if. undefined !== null :-)
Just use:
if (!reviewHeight)
Any falsey value is good enough.
reviewHeight will never be undefined
USE if (!reviewHeight) insted
Maybe best not to use strict comparison for this if statement. Try instead
if (reviewHeight == undefined)
This also enters the if statement if reviewHeight === null.

adding fadeTo Method in Script

I want to add fadeTo to this code snippet. When this adds the class current i want it to fade in. But I don't know how to solve, and where I've have to put the fadeTo(); parameter.
$(this).bind("click", function() {
navClicks++;
$(this).addClass('current').parents('ul').find('a').not($(this)).removeClass('current');
offset = - (panelWidth*z);
alterPanelHeight(z);
currentPanel = z + 1;
$('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
if (!settings.crossLinking) { return false }; // Don't change the URL hash unless cross-linking is specified
});
I'm not exactly sure which DOM element you're looking to fadeTo(), but take a look at this jsfiddle:
http://jsfiddle.net/37XEp/1/
i have a class "current" which i add on click. in your example the "click me" and i want to fade in the green color of your "Click me" text slowly... nevermind the pikachu!

Categories