unable to remove class added by addClass on hover - javascript

i have this simple jquery which adds hide_share class after 10 seconds and it works flawlessely but i want to remove that class when users hovers over that.
.hide_share {
opacity :0.1;
}
this function adds that hide_share class
setTimeout(function() {$("#main_id").addClass("hide_share");}, 10000);
but when users brings cursor i want to remove hide_share class so that it is again visible
seems very simple but wasted my several hours then i searched whole stackoverflow and tried all ideas given by experts but none worked
here is my remove function
$("#main_id").hover(function () {$(this).removeClass("hide_share");} );
when i run same thing in console it works and i can see that class is removed but not directly.
i have tried doing everything even added script tag in head but that also did not work and removed that.
i tried child parameter and everythig,
here is html
<div id="main_id" class="button-position-left hide_share"><div class="button-label"><span>Share</span></div><div class="button2">Img_here</div></div>
can anyone tell where i am doing mistake. i have used similar code and it used to work flawlessely.

Maybe you're looking for this:
$("#main_id").hover(function () {
$(this).removeClass("hide_share");
}, function () {
$(this).addClass("hide_share");
});
setTimeout(function() {$("#main_id").addClass("hide_share");}, 10000);
.hide_share {
opacity :0.1;
}
#main_id {
width: 100px;
height: 100px;
background-color: cyan;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main_id" class="button-position-left"></div>
.hover() method supports 2 parameters: handlerIn and handlerOut. You can set event when user leaves the cusor as the second parameter.

Related

Add a class to an Anchor using a specific smoot-scroll library

I've recently installed the smooth-scroll library from cferdinandi and the smooth-scroll feature works like a charm.
The anchors added to my text using a CMS where looking like this:
<span id="authentication" class="ancre"></span>
The ID being different each time, regarding what I'm talking about in my text. And it works fine.
My problem is that the smooth-scroll library seems to remove the class when it runs, therefore my class='ancre' does not show when the anchor is called. Class being:
.ancre:target{
background-color: #131b24;
color: white;
}
So what I did it that I removed the "target" parameter of my class and added a function to my JS file to add the class after the smooth-scroll is run. It looks like this:
CSS in css/app.css
.ancre{
background-color: #131b24;
color: white;
}
JS in js/app.js
after: function () {
var className = 'ancre';
document.querySelector('.' + className).classList.remove(className);
document.getElementById(anchor.id).classList.add(className);
}
But it does not work and I just couldn't figure out why.
You can try it by pressing the buttons "2-step authentication" and/or "Mobile" on this page.
I'm not a coder, more a designer and I would be happy to get some help here.
Thank you all for your help,
Best,
Kwint
You can use the scrollIntoView javascript function without the need for a library.
https://codepen.io/gezzasa/pen/gzXPbJ/
first I had to set the containers to position: relative; and then set the anchor to position: absolute; top: 0;. with the option on the JS set to block : 'center' it will now only scroll till the anchor is in the middle of the screen.
var smoothScroll = function(e, me) is the function I declared and gets fired on the onclick of the a tag. There are different ways to run the function but this is easy enought. I passed in event on the onclick for the event(event thats fired when you click) and this to tell the script what I clicked on.
e.preventDefault() will prevent the a tag from firing its default function which will reload the page with the href provided. in this case it will append an ID without that script.
document.querySelector(me.getAttribute('href')) will get the ID that it needs to scroll to and then the scrollIntoView function will scroll according to the options that you give it.
Hope I explained it well...I don't have a ton of experience explaining JS.;

Element not hidden on page load

I have the below Javascript code, using jQuery:
$(document).ready(function () {
$('#answer').hide(); //hiding the element
$('#questionOne').click(function () {
$('#answer').show();
However, the element does not get hidden on load. My HTML is this:
<p id="answer">All requests of this nature are required to be submitted via our website www.mufoundation.org/charityrequests. Due to the volume of requests we receive, we require at least 6 weeks notice prior to your event. If your event does not fall within this timescale unfortunately, we will not be able to help.</p>
I cannot seem to hide the paragraph answer element. How can I do this?
If you are always going to be hiding it on load would it not be better practice to not hide it on load and rather attach a CSS class that sets it to hidden? It's extremely simple to do just change your code to do this.
Create a CSS Class called hide
.hide{
display : none;
}
Add the class below.
<p id="answer" class="hide">All requests of this nature are required to be submitted via our website www.mufoundation.org/charityrequests. Due to the volume of requests we receive, we require at least 6 weeks notice prior to your event. If your event does not fall within this timescale unfortunately, we will not be able to help.</p>
If this is literally all the jQuery you have then you have forgotten to add }); }); at the end of the script. So your code should look like this;
$(document).ready(function () {
$('#answer').hide();
$('#questionOne').click(function () {
$('#answer').show();
});
});
if that doesn't fix your problem, are you sure you're including the appropriate jQuery library?
If you posted the right code, then it's the wrong syntax.
Right code
$(document).ready(function () {
$('#answer').hide(); //hiding the element
$('#questionOne').click(function () {
$('#answer').show();
}); });<-- you forgot the clossing brackets
I hope it was that! Let me know if it works.
Create a css class to hide the stuff instead of doing it in onload:
HTML:
<p class="hide">zyz</p>
CSS:
.hide {
display: none;
}
And then, use the following to show it using jquery:
$(document).ready(function () {
$('#questionOne').click(function () {
$('#answer').show();
});
});

.hover not working when used with .html

I am trying to do a simple image rollover with jQuery, but this code is not working:
HTML:
<div class="secondcircle" id="circleone">
<p>
<img src="/../ex/img/group1.png">
</p>
</div>
JS:
$("#circleone").hover(
function () {
$(this).html("<p><img src=\"/../ex/img/group2.png\"></p>");
},
function () {
$(this).html("<p><img src=\"/../ex/img/group1.png\"></p>");
}
);
The mouse enter event fires just fine, but none happens when the mouse leaves.
Moreover, the code works fine with simpler actions - the example in the jQuery docs of appending a span then removing it works just fine.
Why would the html not be working? I've been stuck on this for ages.
Update: Nearly every answer/comment suggests just replacing the image source, and while this works perfectly (thanks!) sometimes I do need to change the HTML (such as to change text). This was just one example. Sorry, I should have better specified that in the question.
Instead of replacing your entire HTML is is a better idea to just change the source of the image.
$("#circleone").hover(function () {
$(this).find('img').attr("src","/../ex/img/group2.png\");
},
function () {
$(this).find('img').attr("src","/../ex/img/group1.png\");
}
);
It works if you adjust it so it just replaces the img, like this:
http://jsfiddle.net/7etUU/
I think the main issue is your div being a block element that spans 100% of the width, then the contents get replaced on hover which removes the content, so it flashes.
Why not do this with CSS?
#circleone {
background-image:url('FirstImageURL');
}
circleone:hover{
background-image:url('SecondImageURL');
}
Totally stole this from this question.
I think your div is taking 100% width. Try adding a "float:left" CSS property. Like this...
.secondcircle{
float : left;
}
I noticed something weird when testing this. His original method does not work until I added a border around the parent div, then it works just fine.
Anyone know why that might be?
jsFiddle
/*UNCOMMENT ME AND I WILL WORK
#circleone
{
border: 1px solid #000;
}*/
You do not need to replace the whole HTML with hover event. If your goal is to change the image on hover, use the attr method instead http://api.jquery.com/attr/:
HTML
<div class="secondcircle" id="circleone">
<p>
<img id="img1" src="http://softwarebyrob.wpengine.netdna-cdn.com/images/football.jpg" />
</p>
</div>
jQuery
$("#circleone").hover(
function () {
$("#img1").attr({ 'src': 'http://softwarebyrob.wpengine.netdna-cdn.com/images/programming.jpg', 'alt':'MyAlt1' });
},
function () {
$("#img1").attr({ 'src': 'http://softwarebyrob.wpengine.netdna-cdn.com/images/football.jpg', 'alt':'MyAlt2' });
}
);
Working JsFiddle here: http://jsfiddle.net/TBMxm/1/
Also, this is better from performance and best practice point of view.
Update1
jQuery Code if you want to use HTML method:
var originalContent = $('#circleone p').html();
$("#circleone").hover(
function () {
$('#circleone p').html('<img src="http://softwarebyrob.wpengine.netdna-cdn.com/images/programming.jpg"/>');
},
function () {
$('#circleone p').html(originalContent);
}
);
Working sample using HTML: http://jsfiddle.net/TBMxm/3/

fadeIn as callback function after fadeOut doenst work as expected

In my HTML a#navInnerMapR and a#navInnerMapL are contained within div#navTwo.
The following code is within a function. When called, I need the function to fadeOut any visible links in div#navTwo, pause for a moment, and then fadeIn a#navInnerMapR.
$('div#navTwo a').fadeOut(200, function() {
$('a#navInnerMapR').delay(100).fadeIn(200);
});
The code fades out the links but doesn't fade anything in. I thought that they delay would only start once the fadeOut finishes, however changing the delay value to 1000 makes it sometimes work but its very buggy. Thanks
UPDATE Here is a fiddle showing that the hidden link starts to be shown before the visible is hidden: http://jsfiddle.net/jamesbrighton/d9QKr/5/
UPDATE Apologies, my question doesnt include the full details of what I need to achieve. I simplified it as I thought I just had some sort of sytax issus that could be easily fixed.
div#navTwo actually contains 3 links. At any point (other than the delay before animations run) only 1 link is visible. I need to be able to call a function that will hide either of the other 2 links that are being shown, and then show a#navInnerMapR.
Different events will call this function, so either of the 2 links that arn't a#navInnerMapR may be visible. Thanks
UPDATE I think this fiddle illustrates the issue. Ive created 2 div.nav's to illustrate different states. Ive hidden different links with inline CSS in each one. JavaScript will be showing and hiding the links in my div repeatedly, so the same div will look like each example at different times.
Ive created 2 triggers to illustrate that different events will need to call the function. When you click on a trigger you can see the issue with both examples. The visible divs are not hidden before the a.one is shown. Thanks for your patience!
http://jsfiddle.net/jamesbrighton/dYvMS/24/
Interesting point, if I change $('.nav a.one').fadeIn(1000); to an alert, the alert fires multiple times! No idea why this would be the case!
Edit: Updated answer based on your below comment,
Yes this works as I need, but im not sure it will work for my actual
page. Sorry for my question not being detailed enough. The code
example I gave is simplified. In the actual page their are 3 links
within div#navTwo, at any time only one of them will be visible. I
need to be able to call a function that hides any links and shows a
specific one, but either one of the other 2 links in div#navTwo may be
visible. Thanks
DEMO
HTML: Added class to all links inside navTwo
<div id="navTwo">
Right
Left
Middle
Upper
Lower
</div>
JS:
$('.links').click(function() {
showHide($(this));
});
function showHide($this) {
$this.fadeOut(1000, function() {
$('#navTwo a').not($this).delay(1000).fadeIn(1000);
});
}
I think I understood what you need. Try below DEMO and let me know if that is what you want,
DEMO
$('#navInnerMapR').click(function() {
runMeR($(this));
});
$('#navInnerMapL').click(function() {
runMeL($(this));
});
function runMeR($this) {
$this.fadeOut(1000, function() {
$('a#navInnerMapL').delay(1000).fadeIn(1000);
});
}
function runMeL($this) {
$this.fadeOut(1000, function() {
$('a#navInnerMapR').delay(1000).fadeIn(1000);
});
}
As you said, You need the function to fadeOut any visible links in div#navTwo, pause for a moment, and then fadeIn a#navInnerMapR (not other links, only a#navInnerMapR).
$('#navTwo a').click(function(e) {
$(this).parent().children().each(function(i){
$(this).fadeOut('slow', function(){
$('a#navInnerMapR').delay(1000).fadeIn(1000);
});
});
});​
A fiddle is here.

setInterval works only the first time

I am trying to use setTimer to animate a slide show using straightforward jQuery. I provide the user with a button (in the form of a "DIV" with a button background image) that he clicks to start the show and which then turns into a pause button. The slides are supposed to change every 3 seconds. Here is the relevant code:
playLink = $('<div id="lbPlayLink" />').click(function(){
$(playLink).hide();
$(pauseLink).show();
slideInterval = setInterval(function(){next()}, 3000)
})[0];
pauseLink = $('<div id="lbPauseLink" />').click(function(){
$(playLink).show();
$(pauseLink).hide();
clearInterval(slideInterval);
}).hide()[0];
The next() function call does the work of replacing the slide with the next one. I have checked out this function and it works perfectly if I call it directly (synchronously), however, when it gets called asynchronously by the setInterval, it works fine the first time (3 seconds after I click on the button), but is never called again, even though it should be called 3 seconds later. I know it's never called as I put an "alert" call at the beginning and end of the function.
If I replace the next() call in the setInterval with alert('test') then I can see the setInterval is doing what it is supposed to. I can't for the life of me see why alert() is OK but next() isn't, unless it has something to do with "scope" of functions, but in that case why does it work the first time?
I've tried debugging the code with firebug, but it can't really help with timeout functions like this. Neither Firefox nor IE8 show any error messages.
I've looked through the various posts here and elsewhere on setInterval, but can't see anything relevant that I haven't tried already. I've been experimenting now for about 3 hours and it's doing my head in. Can anyone suggest what I can try next?
Hmm, I don't like the way you wrote the code, it is not very readable, I would rather suggest something like the following (not tested yet, not sure if it works):
The CSS:
#slides{
/* So you can position your elements under the div#slides */
position: relative;
}
.button {
width: 50px;
height: 10px;
/* So you can position your button anywhere you like */
position: absolute;
bottom: 10px;
right: 10px;
}
.play {
background:url(..) no-repeat;
}
.pause {
background:url(..) no-repeat;
}
The HTML consist of the parent slides holding everything relating to slides, and the controller, basically holds your button image.
<div id="slides">
<div id="controller" class="button play"></div>
</div>
The code:
(function() {
//Let's wrap everything in an anonymous function, so to avoid variable confusion
function next() {
//Assume this is your code doing the sliding. I don't touch
}
var invt;
function play() {
//Always clear interval first before play
if (invt) clearInterval(invt);
invt = setInterval(function() {
next();
}, 3000);
}
function pause() {
if (invt) clearInterval(invt);
}
$(document).ready(function() {
$('#controller').click(function() {
//It's not playing so it has the play class
if ($(this).hasClass('play')) {
$(this).removeClass('play').addClass('pause');
pause();
}else{
$(this).removeClass('pause').addClass('play');
play();
}
});
});
})();
change this line on both:
$('<div id="lbPlayLink" />').click(function(){
to:
$('<div id="lbPlayLink" />').live("click", function(){
To clarify how I solved the problem:
I took onboard Ivo's suggestion to have a single button (though in the form of a "DIV" element rather than a "BUTTON") and change the class of this button between "lbPlay" and "lbPause" to change the background image and trigger the correct action.
My main problem was that I was unknowingly setting the event on this button multiple times and I believe this is what was causing the strange behaviour.
I got round it by putting the return code from the "setInterval" call into a variable ("ppHandler") attached to the DIV, using the jQuery "data" method.
The new code is:
if (typeof($(playPauseLink).data('ppHandler')) == 'undefined'){
$(playPauseLink).click(function(){
var $this = $(this);
if ($this.hasClass('lbPlay')) {
if ($this.data('ppHandler') != -1) clearInterval($this.data('ppHandler'));
$this.data('ppHandler', setInterval(function(){next();}, slideInterval*1000));
$this.removeClass('lbPlay').addClass('lbPause');
} else {
if ($this.data('ppHandler') != -1) clearInterval($this.data('ppHandler'));
$this.data({ppHandler: -1});
$this.removeClass('lbPause').addClass('lbPlay');
}
});
Thanks to all who responded. To see the final result go to "www.trips.elusien.co.uk" and click on the "slimbox examples" link and go to "example 9".

Categories

Resources