$.delay() and setTimeout() issue in javascript/jQuery. Which will win? - javascript

This is a small javascript/jQuery program where the user starts with a portfolio of 20K and, when one inputs an amount and clicks on 'buy', the program then evaluates if you have enough money to do so. If you don't, then a message appears saying that you have insufficient funds. I want that message to stay on the screen for at least 5 seconds and, ideally, fadeout slowly afterwards. I've tried both the $.delay() method with jQuery and the setTimeout() method and both don't work. Any idea why?
JavaScript/jQuery:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
Some other code that works:
JS :
$("#buttonBuy").click(function() {
amount= document.getElementById('investment').value
if (/*you have enough money*/){
//do something
}
else
{
//1st option (setTimeOut): it doesnt respect the delay for some reason,only shows up for about 1 sec
document.getElementById('insufficientFunds').innerHTML= "Insufficient funds! ";
setTimeout(function(){
document.getElementById('insufficientFunds').innerHTML= "";
}, 5000);
}
});
//2nd option (delay method) : I get error--> Failed to execute 'query SelectorAll on element: *;x is not valid selector
$(function () {
$('#insufficientFunds').fadeIn('slow', function () {
$(this).delay(5000).fadeOut('slow');
});
});
};
HTML :
<form>
<input type="text" id="investment" <br>
<button id="buttonBuy" >Buy</button>
</form>
<p>Portfolio Value :</p>
<p id="portfolio"></p>
//1st option
<p id="insufficientFunds"> </p>
//second option
<p hidden id="insufficientFunds" > insufficient funds! </p>

I can't repeat your error, but this code seems to be working.
$("#buttonBuy").click(function () {
amount = document.getElementById('investment').value
if (true) {
$(function () {
$('#insufficientFunds').fadeIn('slow', function () {
$(this).delay(5000).fadeOut('slow');
});
});
};
});
JSFiddle

Related

Get a dynamic element to change text

I have a dynamic element in my web page like this that appear when I click on an icon:
<span class="elasticbar-item text-right text-baseline">
<button class="button primary" data-next-button="">MY TEXT</button>
</span>
But I want to change default text that come from server (where I don't have access) with a new text.
What I tried before now is represented by:
var buttonIntervalCheck = setInterval(function () {
var button = $("[data-next-button]");
if(button.length === 1) {
button.text("NEW TEXT");
clearInterval(buttonIntervalCheck);
}
}, 1000);
Example in Google Chrome
First result is when I clicked on my icon.
Second result is when I make Inspect on the button (Ctrl+Shift+I) on the button.
And I don't understand how exactly works.
How I can fix it?
Try running this on your console:
$("[data-next-button]").text("NEW TEXT");
If it works correctly, then your timing is wrong. You are probably calling button.text before the DOM has loaded. Try wrapping your code around the ready fuction:
$(function() {
var buttonIntervalCheck = setInterval(function () {
var button = $("[data-next-button]");
if(button.length === 1) {
button.text("NEW TEXT");
clearInterval(buttonIntervalCheck);
}
}, 1000);
});
You can't select a dynamic element with jquery , try with js like
document.querySelector("[data-next-button]")
In the example below there is a setTimeout() that adds the button in the HTML dynamically in 5 seconds. Then, the setInterval() changes the text of the button and close the interval. Everything worked as you expected. I don't see any error here.
var buttonIntervalCheck = setInterval(function () {
var button = $("[data-next-button]");
if(button.length === 1) {
button.text("NEW TEXT");
clearInterval(buttonIntervalCheck);
}
}, 1000);
setTimeout(function(){
$('#ss').html(`<span class="elasticbar-item text-right text-baseline">
<button class="button primary" data-next-button="">MY TEXT</button>
</span>`);
}, 5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='ss'></div>

set Interval function is not working in jsp?

The setInterval function is not working in my jsp page, below is my code:-
<script>
$(document).ready(function(){
$('form[name="lgform"]').submit(function(evnt){
evnt.preventDefault();
try{
mapPlotVar.clearInterval();
}
catch(e)
{
}
mapPlotVar=setInterval($("#btn_login").click(function(){console.log("update");},20000));
});
$("#btn_login").click(function(){
alert("hi");
});
});
</script>
<body>
<form name="lgform">
<div>
<table id="table" >
<tr>
<td width="35px"><input id="mob" type="text" name="mob_nu" placeholder="1234567890" maxlength="10"></td>
<td width="100px"><input type="button" name="login_btn" id="btn_login" value="Login"></td>
<td width="100px"><label for="Login" style="color: red" id="login_val"></label></td>
</tr>
</table>
</div>
</form>
</body>
</html>
After clicking the "btn_login" once i want the function to be called after every 20 seconds so that i get the alert message "hi" after every 20 seconds, but "hi" is only showing once, setInterval function is not working. What is wrong with my code? Any piece of code is appreciated.
I tried to use the set Interval here in a different manner because, i want the function to be called just after my first click and continue after every 20s and it wont work if we put the set interval function inside the function we call on button click in usual way.
Thanks in advance
setInterval($("#btn_login").click(function(){console.log("update");},20000));
The above will call jQuery.click once and pass its return value (a jQuery object) to setInterval but setInterval expects a callable function as its first argument.
The correct way to do it by wrapping into an anonymous function:
setInterval(function() {
$("#btn_login").click(function(){console.log("update");})
}, 20000);
But this still makes not much sense, since this way a new click event handler will be added (but not executed) to element every twenty seconds.
Your code has a lot of problems. Ignoring the other issues, if you want to set a 20s interval for a function on button click, you need to kick off the interval inside of the click handler.
$("#btn_login").click(function(){
setInterval( function () {
alert('hi');
}, 20000);
});
Of course, this will then happen on every button click. One way to solve it would be to use .one('click', function() { setInterval...}) instead of .click() because it will then work on first click only. But since it looks like you also want to cancel the interval, you'll need to take care of that as well.
edit:
var interval;
$("#btn_login").one( 'click', function() {
function run () {alert('hi');}
run();
interval = setInterval( run, 20000 );
});
// you can now cancel this interval somewhere else
function someCallback () {
if ( interval )
clearInterval(interval);
}
There are four basic things wrong with your code:
You do everything when the form is submitted, but you have no mechanism to submit the form (and your description says you don't want it to trigger on submission anyway).
Your code to tell the browser do stuff when the button is clicked is being passed to setInterval instead of the other way around.
You aren't passing a function to setInterval.
The code you want to run every time period is nowhere near your interval code
You need to throw out most of the code and start again.
var interval;
function run_on_interval_when_button_is_clicked(){
alert("hi!");
}
function run_when_button_is_clicked(event) {
event.preventDefault();
interval = setInterval(
run_on_interval_when_button_is_clicked,
20000
);
}
$(document).ready(function(){
$("#btn_login").on('click', run_when_button_is_clicked);
});
None of this has anything to do with JSP. That's server side code.
var interval;
$('#btn').on('click',function(){
if(typeof (interval) === 'undefined') {
interval = setInterval(function(){
alert('hi');
},20000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Click</button>
$('#btn_login').on('click', function(){
setInterval(function(){ console.log("update"); }, 20000);
});

How I can repeat a function in jQuery?

I tried using an infinite loop within this function however, when I set up the setInterval the function doesn't repeat. The problem is when the user sends the form and after the time interval passes. The function stays on the sent message and doesn't start from the beginning. Please see my JSBin.
Javascript:
$(function(){
function show_fb() {
$("#feedback_box").show("slow");
}
function hideAll() {
$("#feedback_box").hide("slow");
}
$("#feedback_box #close").click(function() { // When the X is pressed
$("#feedback_box").hide("slow"); // Hide the form
});
setInterval(show_fb,1000); // Show the form after 6 seconds , you can change 6000 to anything you like
$("#feedback_form").submit(function() { //When the form is submitted
$('#feedback_form #fb_title').css('background-color','#4444FF').text('Sending...').slideDown(900); //show "Sending" message
$.post("form_submit.php",{ mesaj:$('#mesaj').val(),rand:Math.random() } ,function(data) { //subimit the feedback via AJAX
$('#feed_subm').attr("disabled", "false"); //disable the "SEND" button
$('#feedback_form #fb_title').css('background-color','#C33').text('Thank You!').slideDown(900); //Shows a thank you message
setTimeout(hideAll,2000); // Hide the form after 2 seconds
});
});
return false; //Tells the code not to post the form physically
});
HTML:
</head>
<body>
<div id="feedback_box">
<form id="feedback_form">
<span id="fb_title">Give us some feedback :)</span><span id="close">X</span>
<textarea id="mesaj"></textarea>
<input type="submit" value="Send" class="mysubm" id="feed_subm"/>
</form>
</div>
</body>
You can repeat a function in jQuery like this:
Javascript:
$(document).ready(function() {
// First we will create the function that will be repeated
function repeat() {
setTimeout(function() {
// Enter your code that you want to repeat in here
repeat(); // This is where the function repeats
}, 1); // Where 1 is the delay (in milliseconds)
}
repeat(); // Here we are initially firing the function
});
In your example above, I can't see why you would need a function constantly being repeated however your question was How I can repeat a function in jQuery?
Which I think means How can I repeat a function in jQuery?
Well here's your answer.

jQuery : Clear Interval not working after stop button click

I'm trying to stop a loop after bt_stop click. But it is not working fine. clearInterval is not woking after the stop button is clicked.
<div id="abc">
<input id="bt_go" type="button" value="go" />
<input id="bt_stop" type="button" value="stop" />
<div id="output"></div>
</div>
<script>
$('#bt_stop').click(function () {
Get_close('','user1');//enter code here
})
$('#bt_go').click(function () {
Get_close(''#output'',user1');
});
function Get_close(id, output) {
if (id!= '') {
id = setInterval(function () {
chatMSG(id, outpu);
}, 1000)
}
else {
clearInterval(id);
alert('stop');
}
}
</script>
There's quite a bit missing from this code that would make it work. There's at least 3 forseeable errors, some are syntax and some are logic so off we go!
1) $('bt_stop') and $('bt_go') should be $('#bt_stop') and $('#bt_go')
2) chatMSG doesn't even exist in your code so unless you're including it somewhere else that'll be an error. (also outpu should probably be output)
3) When calling Get_close() you shouldn't need to double single quote ''#output'' like that. You can just do '#output'
If you do all these things then it should work.
In order to select an element using its id you shoud add '#':
$('#bt_stop')
Here is an example of what you are trying to do: http://jsfiddle.net/FpgLh/
Good Luck!

Changing jQuery function to page load

Can anyone tell me how to change the following statement which is currently controlled by a radio button to a document load function.
Basically I want the slide div to slide out from the left to right when the page loads.
jQuery:
jQuery(function() {
jQuery('#slide').hide();
jQuery(':radio[name=radiobutton]').click(function() {
var value = $(this).val();
if (value === 'Y') {
jQuery('#slide').show('slow');
} else if (value === 'N') {
jQuery('#slide').hide('slow');
}
});
HTML:
<div id="slide" class="alpha60">
<p class="statement_style_head">Content goes here</p>
<p class="statement_style_text">A line or two of text goes here </p>
</div>
$(document).ready({. Your staff. });
One way is to just click it on load like so $('input[name=radiobutton]').click(); or $('input[name=radiobutton]').trigger('click');
The other would be to place your code inside a function and call that function on load.
function showSomething(){
// code here
}
showSomething();
Document.ready is kind of onload for javascript , it waits till everything is ready and then executes...your code , it safe and best practices for onload
$(document).ready(function() {
$("divid").animate({top:'10px', bottom:0}, 3000);
});

Categories