Upon Link Click and setTimeout - javascript

In JavaScript, I am trying to execute a function 2 seconds after a link is clicked, and wait until the function completes its execution before going to the link destination.
/* JavaScript */
function myFunction() { /* Block of code, with no 'return false'. */ }
<!-- HTML -->
<a onclick="setTimeout(myFunction, 2000);" href="http://www.siku-siku.com">Link</a>
The problem is upon click, the browser immediately goes to the link destination i.e. myFunction didn't have time to execute. Did I miss anything here?
Thanks beforehand.

You will need to return false from your onclick event, to cancel the actual browser handled page load.
And since you want to follow the link (once the function is complete) you will need to do that through javascript. But you are using a timeout so you loose the reference to the clicked element, so we need to pass that too in the method (if you want this logic for multiple links)
html
<a onclick="return createTimedLink(this, myFunction, 2000);" href="http://www.siku-siku.com">Link</a>
javascript
function createTimedLink(element, callback, timeout){
setTimeout( function(){callback(element);}, timeout);
return false;
}
function myFunction(element) {
/* Block of code, with no 'return false'. */
window.location = element.href;
}
demo at http://jsfiddle.net/gaby/mdkjX/2/

<a onclick="setTimeout(myFunction, 2000);" href="#">Link</a>
JAVASCRIPT
function myFunction(){
////your other code
///
///
window.location="http://www.siku-siku.com";//at the end
}
demo here

Yes, the default behavior for a link is a GET request sent by the browser. Imagine that before you register your handler, browser has registered another handler to initiate a get request (just imaginary). This is the case here. You should return false in your inline handler:
onclick = '(function(){ setTimeout(yourFunction, 2000); return false;})()'
or more simpler:
onclick = 'setTimeout(yourfunction, 2000); return false;'
Update:
Use this (it requires jQuery):
$(function () {
$('a').click(function (e) {
e.preventDefault();
var target = $(this).attr('href');
setTimeout('go("' + target + '")', 2000);
});
});
function go(target) {
console.log('2 seconds passed');
document.location = target;
}

Related

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 to make onclick to fire when javascript returns false

The onclick doesn't work when the javascript returns false. I need javascript to return false in order to animate the button. If I return true then the onClick works but the animation doesn't work. I have tried doing __doPostBack and UseSubmitBehaviour but nothing seems to work. Any help would be really appreciated on how to fix this.
Code for asp button:
<asp:LinkButton id="btn_salaries" onClientClick="return fncsave();" OnClick="btn_clicked" UseSubmitBehavior="false" runat="server" type="button" class="list-group-item" Text="getCharitySalaries"/>
Javascript code:
function fncsave(){
$(document).ready(function(){
$("#list").click(function(){
$("#list_of_btns").animate({left: '-290px'});
});
});
return false;
}
Update:
I'm doing the animation in ajax but I don't know if I'm doing this correctly because it does not perform the animation.
This is my code below:
function fncsave(){
alert("dsfdsf");
$(document).ready(function(){
$(document).ajaxStart(function(){
$("#list_of_btns").animate({left: '-290px'});
}
}
return true;
}
You should not check for document ready event on the click event handler. Also, when someone clicks on the link you are calling fncsave function but inside that function you are subscribing to another event (click) on the tag with id list.
If I understand correctly, you should do this:
function fncsave(){
$("#list_of_btns").animate({left: '-290px'});
return false;
}
Just as a comment, "return false" means that it's not gonna continue with the normal flow of the event handling, which is submit the form.
If you return true, the form is submitted. That means the form data is sent to the server and the C# code is executed. Then, the page if fully reloaded (from scratch). In that case, the animation makes no sense and you'll need AJAX to perform an animation while the C# code is running. See this tutorial about AJAX (Tutorial about AJAX).
Try like this
function fncsave(){
$("#list").click(function(){
$("#list_of_btns").animate({left: '-290px'},900,function(){
return false;
});
});
}
I have a 'animated' variable with default is false. If button is clicked, check if animated is false, 'preventDefault()' cancel the submit, play animation, 'setTimeOut()' will the function after 3000ms, assign animated to true, and trigger 'click' on the button. This time, animated is true and it post data to server.
<asp:Button ID="btn_salaries" OnClick="Button_Click" runat="server" type="button" Text="getCharitySalaries" />
<br />
<script type="text/javascript">
$(document).ready(function (e) {
var animated = false;
$('#' + '<% = btn_salaries.ClientID %>').click(function (ev) {
if (!animated) {
ev.preventDefault();
$(this).animate({ left: '-290px' });
setTimeout(function () {
animated = true;
$('#' + '<% = btn_salaries.ClientID %>').trigger('click');
}, 3000);
}
});
});
</script>
Hope this help.
This should do what you want.
function fncsave(){
$("#list_of_btns").animate({left: '-290px'},900,function(){
// Do __doPostBack here
});
return false;
}
It'll delay doing the post back until after the animation is done. An alternative would be to use update panels to avoid the flicker from the post back that'll follow the animation.

Changing jQuery Event from click to on load

I am using the following onclick function that triggers the object to become full screen when clicked. I want the object to be fullscreen when the page loads without having to click.
fbNav.find('ul li.fullscreen').on('click', function(e){
if(!fullscreen) {
fbFullscreen.show();
fbFullscreen.append(fbCont);
$window.trigger('resize');
} else {
fbParent.append(fbCont);
fbFullscreen.hide();
$window.trigger('resize');
}
fullscreen = !fullscreen;
});
How can i achieve this?
You better put the main logic in a function and call the same function on ready and click.
function fullscreen(){
if(!fullscreen) {
fbFullscreen.show();
fbFullscreen.append(fbCont);
$window.trigger('resize');
} else {
fbParent.append(fbCont);
fbFullscreen.hide();
$window.trigger('resize');
}
fullscreen = !fullscreen;
}
//will be executed when page loads
$(document).ready(function(){
fullscreen();
});
//will be executed on click
fbNav.find('ul li.fullscreen').on('click', function(e){
fullscreen();
});
You can trigger click event on page load.
fbNav.find('ul li.fullscreen').trigger("click");

button onclick function is unnecessarily reloading the page after the function execution

Here is a button onclick which calls a function. When this button is clicked after the function execution, the page is getting reloaded in firefox browser.
<button id="next" class="submit" type="submit" onclick="onNextEvent()" return false;>Next</button>
When
event.stopImmediatePropagation();
event.preventDefault();
are removed from this
function, the page is getting reloaded in Chrome browser.I am using Jquery jquery - 1.9.1.js.Please help!Thanks
function onNextEvent() {
event.stopImmediatePropagation();
event.preventDefault();
if ($('.current').hasClass('first')) {
$('.current').removeClass('current').hide()
.next().show().addClass('current');
$('#prev').show();
$('#prev').attr('disabled', null);
$('#skip').show();
return;
}
}
Try this:
function onNextEvent(event)
{
event.preventDefault();
/* Rest of code */
Or
function onNextEvent(event)
{
event.stopImmediatePropagation();
/* Rest of code */
The return false statement should be implemented together with the onclick like this:
<button onclick="onNextEvent(); return false;">
Or, the function called can return false:
function onNextEvent() {
//function code
return false;
}
I have used the first way several times and it always worked for me.

Calling JS functions from Href

I'm curious whats the best way to call a JS function with a href link in HTML. I don't use a library and i see alot of mention about jquery using event handlers ...
But if im not using a library can it still be done or will i have to use an on click type call ?
You can use event handlers with plain javascript. No framework is required. Here's a cross browser function I use:
// add event cross browser
function addEvent(elem, event, fn) {
if (elem.addEventListener) {
elem.addEventListener(event, fn, false);
} else {
elem.attachEvent("on" + event, function() {
// set the this pointer same as addEventListener when fn is called
return(fn.call(elem, window.event));
});
}
}
And, an example of using it would be like this:
HTML:
<a id="myLink" href="#">Click ME</a>
Javascript:
var link = document.getElementById("myLink").
addEvent(link, "click", function(e) {
// process the click on the link here
});
If you don't want the default click of a link to happen, then you need to prevent the default behavior from the event handler like this:
var link = document.getElementById("myLink").
addEvent(link, "click", function(e) {
// process the click on the link here
// prevent default action of the click
if (e.preventDefault) {
e.preventDefault(); // normal browsers
} else {
e.returnValue = false; // older versions of IE (yuck)
}
});
try this
function test() { alert (''); }
<a href="#" onclick="test();" />
Basically there are two ways:
...
and
...
(in this case someFunction must return false)
I prefer the latter.

Categories