Nesting jQuery functions within functions - javascript

Below is the code I am working on
$("#firstnamesubmitbutton").click(function(){
$(".hrmed").addClass("lineanimation", function(){
$(".firstnamesection").addClass("animate fadeOut");
$(".firstnamesection").addClass("hidden");
$(".hrmed").removeClass("lineanimation");
$(".lastnamesection").removeClass("hidden");
alert("Code was executed");
});
});
I am trying to created a nested jQuery function so that the rest of the code is called after the "lineanimation" class has been added but when I run this code the "lineanimation" class is added and the rest of the commands are not executed. Can anyone help me understand the correct syntax to solve my problem?
Thanks in advance

As I'd mentioned above, .addClass() is instant. As such, it does not take a callback method. Additionally, it has no way of inherently knowing the duration of your CSS transition.
Instead, you could use setTimeout(). It will execute a given function after waiting X milliseconds.
The first argument would be the function you've written in your question. The second parameter corresponds to the length of your CSS animation.
(For example, a 3s animation would be 3000.)
$("#firstnamesubmitbutton").click(function() {
var $hrmed = $(".hrmed");
$hrmed.addClass("lineanimation");
setTimeout(function() {
$(".firstnamesection").addClass("animate fadeOut hidden");
$hrmed.removeClass("lineanimation");
$(".lastnamesection").removeClass("hidden");
console.log("Code was executed");
}, 3000);
});
.hrmed {
padding: 50px;
border: 1px solid black;
}
.hrmed.lineanimation {
background: blue;
transition: background 3s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="firstnamesubmitbutton">Click me</button>
<div class="hrmed"></div>

Editted
$("#firstnamesubmitbutton").click(function(){
$('.hrmed').delay(1000).queue(function () {
$(this).addClass('lineanimation').dequeue();
}).delay(2000).queue(function () {
$(".firstnamesection").addClass("animate fadeOut");
$(".firstnamesection").addClass("hidden");
$(".lastnamesection").removeClass("hidden");
$(this).removeClass('lineanimation');
alert("Code was executed");
});
});
.hidden {
display: none;
}
.lineanimation {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="firstnamesubmitbutton">Click</button>
<div class="hrmed">
<div class="firstnamesection">firstname</div>
<div class="lastnamesection">lastname</div>
</div>

Related

How do I wait for this animation to finish before moving on to the next one?

I am creating a game with HTML, CSS, & JavaScript. I have 5 h2(s) and I want to wait for the animation to finish before moving on to any part of the code. The animation works how I want it to but the JavaScript is starting the next animation before the first one is even done! I have tried using
window.setTimeOut
but no luck. Here is the code with the required code: https://codepen.io/HumanFriend/pen/mdOBvoL
Can someone help me?
You can listen to animationend event, fe:
const animated = document.querySelector('.animated');
animated.addEventListener('animationend', () => {
console.log('Animation ended');
});
Read more: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/animationend_event
Random thing:
When you use setTimeout(nextI_ifelse(), 5000); you just invoke the nextI_ifelse inline (and you're setting timeout for the value returned from this function). Change it to setTimeout(nextI_ifelse, 5000);
Any you just want to read about algorithms in general. What you try to do makes sense, but the way you're trying to achieve that does not. The for loop in your codepen runs instantly, so iLevel is directly set to the last value.
To elaborate on entio's answer, your animation occurs when an element has the class "typing-effect." When that animation ends, the browser calls an event called "animationend." You can use JavaScript to run your animation on the next element by accessing that event.
Notice in HTML the snippit below, I've moved the "display: hidden" to a CSS class and removed the "typing-effect." In my JavaScript function, I enable the class in the first element, increment the counter, and told the "animationend" to call the function again with the new value for "i."
Edit: I forgot to mention, I modified the id values. I don't believe a valid id value in HTML5 can contain parenthesis.
console.log("script.js connected");
let iLevel = 1;
let loop = 0;
function animateNext(i){
let stop = document.querySelectorAll('.animated').length;
let animated = document.querySelector(`#h2_${i}`);
animated.classList.add('typing-effect');
animated.addEventListener('animationend', () => {
if(i===stop){
iLevel = "iDone";
}else{
animateNext(i+1);
}
});
}
function startGame() {
animateNext(1);
}
.animated{
display: none;
}
.typing-effect {
display: block;
animation: typing-effect 5s steps(130, end), 0.75s step-end infinite;
white-space: nowrap;
overflow: hidden;
border-right: 2px solid black;
}
.typing-effect:after {
content: " ";
}
#keyframes typing-effect {
0% {
width: 0%;
}
100% {
width: 100%;
}
}
#keyframes blink-caret {
from,
to {
border-color: transparent;
}
50% {
border-color: black;
}
}
<button onclick="startGame();">START GAME</button>
<div id="instructions">
<div>
<h2 id="h2_1" class="animated">Welcome to The Number Wizrd</h2>
</div>
<div>
<h2 id="h2_2" class="animated">Adjfosdf</h2>
</div>
<div>
<h2 id="h2_3" class="animated">sosidjfs</h2>
</div>
<div>
<h2 id="h2_4" class="animated">difjspodf</h2>
</div>
<div>
<h2 id="h2_5" class="animated">skidjfosidf</h2>
</div>
</div>

jquery slideDown, slideUp wiggling

I am new to jquery and have problem with one part of my script. basically I am making dropdown div when mouse is over the button, but div starts moving up and down like crazy. here is what i have done: `
<script type="text/javascript">
public var boolean opened = false;
$("#drop1").slideUp();
$("#first").mouseover(function(){
$("#drop1").slideDown();
});
$("#first").mouseout(function(){
$("#drop1").slideUp();
});
});
also I tried using boolean variable but it gives me error.
<script type="text/javascript">
$(document).ready(function(){
public var boolean opened = false;
$("#drop1").slideUp();
$("#first").mouseover(function(){
if(!opened){
$("#drop1").slideDown();
opened = true;
}
});
$("#first").mouseout(function(){
if(opened){
$("#drop1").slideUp();
opened = false;
}
});
});
here is HTML if you want, but I think there is everything ok.
<link rel="stylesheet" type="text/css" href="design.css">
<div id="first" style="position: absolute; left: 0px;">
<a class="btn" href = "TheShooter/Launcher.exe" ><b>LAN shooter project</b></a>
<div id="drop1">
<em>shooter project main page</em> <br/>
info: Local Area Network multiplayer game, made with unity. Project not finished yet, but sometimes fun to play. <br/>
controls: walking: w,a,s,d<br/>
shoot: LMB.<br/>
zoom: RMB.
</div>
</div>
Thanks for any help.
--Nick.
So it looks like you might be more used to strongly typed languages like C#. JavaScript and its library jQuery are loosely typed, meaning you don't declare scope or type. Here's your code above cleaned up a bit to use correct syntax and solve the issues you're seeing:
$(document).ready(function(){
var opened = false;
// Instead of sliding this up, give the #drop1 element
// a property of display: none; to start - then remove the line below
$("#drop1").slideUp();
$("#first").mouseover(function(){
if(!opened){
// Below, I'm using a callback, which means the boolean
// won't update to true until after the animation is finished
$("#drop1").slideDown(400, function() {
opened = true;
});
}
})// Since it's the same element, we can chain events
.mouseout(function(){
if(opened){
// Another callback
$("#drop1").slideUp(400, function() {
opened = false;
});
}
}
});
});
Let me know if you have any questions about the above!
Hi please refer this fiddle which should answer your question. No need to add any boolean or conditional checking:
<div id="wrap">
<div id="text">text</div>
<div id="video">video</div>
and js
$(document).ready(function(){
$("#wrap").mouseover(function(){
$("#video").stop().slideDown("slow");
});
$("#wrap").mouseout(function(){
$("#video").slideUp("slow");
});
});
and css
#text
{
margin-top:20px;
float:center;
font:VNF-Museo;
font-size:40px;
color: #333;
margin-left:auto;
margin-right:auto;
border: 1px solid #000;
}
#video
{
display:none;
width:1024px;
height:278px;
border: 1px solid #000;
}
I think you should try something like this:
$(document).ready(function() {
$("#first").mouseover(function(){
$("#drop1").slideDown("slow");
});
$("#first").mouseout(function(){
$("#drop1").slideUp("slow");
});
});
See this example above, from the jQuery offical documentation, for more information:
http://api.jquery.com/mouseover/
http://api.jquery.com/mouseout/
Here is one more answer with live example,
$(document).ready(function(){
$("#drop1").mouseover(function(){
$("#first").slideDown("slow");
});
$("#drop1").mouseout(function(){
$("#first").slideUp("slow");
});
});
#first, #drop1 {
padding: 5px;
text-align: center;
background-color: #acacac;
border: solid 1px #c3c3c3;
}
#first {
padding: 50px;
display: none;
background-color: skyblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div id="drop1">Mouse over on panel to slide down</div>
<div id="first">Hello Stackoverflow ..!</div>

jquery loading content unnecessarily

$('.blue-anim').hover(function(){
setTimeout(function(){
$('.blue-anim').load('/web #physics')
}, 1000);
$('.bluefigcaption').text("Physics").removeClass('blue_figcaption').addClass('new_caption');
}, function(){
$('.blue-anim').load('/web #past');
$('.blue figcaption').text("Past").removeClass('new_caption').addClass('blue_figcaption');
}
);
This is my java script for hover an image. The hover in works correctly as it replaces as image with another image with load(). The hoverout also works which essentially brings back the old image. But just after the hoverout jquery again bring the hoverin image back. When I check in firebug, I see that the load() function in hoverin in again being run. Just the load() function nothing else. Why is it happening? Is the load script embedded in the html or something? If so how can I remove it?
I tried to reassemble your code, this
$(function () {
$(".blue-anim").hover(function() {
$(".blue-anim").load("https://raw.githubusercontent.com/xxxmatko/xDev.RequireJs/master/README.md");
$('.blue-figcaption')
.text("Physics")
.removeClass('blue-figcaption')
.addClass('new-caption');
}, function() {
$(this).load("https://raw.githubusercontent.com/xxxmatko/xDev.Boilerplates/master/README.md");
$('.new-caption')
.text("Past")
.removeClass('new-caption')
.addClass('blue-figcaption');
});
});
.blue-anim {
background: blue;
width: 600px;
height: 200px;
}
.blue-figcaption {
color: blue;
}
.new-caption {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="blue-anim">
</div>
<div class="blue-figcaption">
</div>
works for me

How can I hover multiple elements in order with using jquery?

I want to hover all div under .wrapper div in order with a delay when the page is loaded. How can I do this with using jquery?
HTML
<div class="wrapper">
<div class="first"></div>
<div class="second"></div>
<div class="third"></div>
</div>
Jquery
$('.wrapper').children().each(function(){
$(this).trigger('hover');
});
https://jsfiddle.net/drxvr1hn/
.trigger('hover') has been deprecated as it caused a great deal of maximum stack exceeded errors.
Deprecated in jQuery 1.8, removed in 1.9: The name "hover" used as a shorthand for the string "mouseenter mouseleave". It attaches a single event handler for those two events, and the handler must examine event.type to determine whether the event is mouseenter or mouseleave. Do not confuse the "hover" pseudo-event-name with the .hover() method, which accepts one or two functions.
Trying to trigger the hover state via jQuery is a very browser/cpu intensive process and a lot of re-rendering of a page to ensure that your call is correct. Therefore the ability was removed but is possible with some JS but will almost certainly cause speed issues and/or stack issues which can cause browser crashes.
A good alternative would be to use classes like below:
$(document).ready(function() {
$('.wrapper div').on('mouseover', function() {
$('.wrapper div').addClass('hover');
}).on('mouseleave', function() {
$('.wrapper div').removeClass('hover');
});
});
.wrapper > div {
width: 100%;
height: 20px;
margin-bottom: 20px;
}
.first {
background-color: #468966;
}
.second {
background-color: #FFF0A5;
}
.third {
background-color: #FFB03B;
}
.first.hover {
background-color: #B64926;
}
.second.hover {
background-color: #8E2800;
}
.third.hover {
background-color: #464A66;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="first"></div>
<div class="second"></div>
<div class="third"></div>
</div>
you need to set the timeOut interval
$(window).scroll(function() {
$('. wrapper'). children().each(function(index){
var _this = this;
setTimeout( function(){ $(_this).trigger('hover'); }, 200*index);
});
});

Add Callback to Dequeue

Does anyone know how to add a callback after a dequeue in jQuery has been completed? If not, can you provide me with how to add a delay to a dequeue? Thanks a million!
Might need more info, but if you are trying to have some code called after a particular queued item is dequeued, you could wrap the original queued function with your own. For example, you could change from:
$("#xyz").queue(someFunction);
to this:
$("#xyz").queue(function() {
someFunction();
// your callback code here
});
I'm assuming that "someFunction" calls dequeue in order to keep the sequence going.
You can use a promise (http://api.jquery.com/promise/). Here is some code I (literally) just wrote which ensures that some divs are finished hiding before a show etc on them is started. The function passed into the done call on the promise will only get run after all the effects are finished. I put the next() (=>dequeue) call in there so the next queued item gets run.
<style>
#pieces { width: 300px; height: 100px; background-color: lightblue;}
#pieces .piece { width: 75px; height: 75px; border: 1px solid grey; float: left;}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
var q = $({});;
function hidePieces() {
q.queue(function(next){
var pieces = $($("#pieces .piece").get().reverse());
pieces.each( function(i) {
$(this).delay(300*i).slideUp(1000);
});
pieces.promise().done(function(){ next(); });
} );
}
function showPieces() {
q.queue(function(next){
var pieces = $("#pieces .piece");
pieces.each( function(i) {
$(this).delay(300*i).slideDown(1000);
});
pieces.promise().done(function(){ next(); });
} );
}
$(function(){
for( i=0;i<5;i++ ){
hidePieces();showPieces();
}
});
</script>
<div id="pieces">
<div class="piece" id="p1"></div>
<div class="piece" id="p2"></div>
<div class="piece" id="p3"></div>
</div>

Categories

Resources