How to prevent onmouseover function from firing continuously - javascript

When I mouseover a button, a function activated by onmouseover fires continuously every fraction of a second. I want it to fire only once.
I need to use onmouseover on a button to call a submit function because I cannot use onclick because it interferes with another function that is called onclick. If I use onmouseout it works ok and only fires once, but onmouseout is not satisfactory for my purpose. I have tried other event handlers including onmouseenter, and onmousedown, but they suffer from the same problem. I also tried this: onmouseover="submitForm(); button.onmouseover = null;"
<script language="javascript" type="text/javascript">
function submitForm() {
$("#pform").submit();
}
</script>
<input type="button" onmouseover="submitForm();" />
When the button is moused over, the function fires continuously, several times per second. I want it to fire only once.

You can use simple logic to check whether the mouse over event enters first time. Use local storage, if local storage is no set initially, it is the first time the mouse over event.
else if local storage is already set to true, then don't trigger the form submit.
<script language="javascript" type="text/javascript">
function submitForm() {
if(sessionStorage.getItem("mouse_over") == undefined){
sessionStorage.setItem("mouse_over","true");
$("#pform").submit();
}else{
}
}
</script>
<input type="button" onmouseover="submitForm();" />

$(element).one('mouseover' function(){
// your function here
});

Apparently, when you submit the form, the page is reloaded. After the reload, the mouse is still on the button and the event is fired again.
It is not common to use onmouseover to submit a form. You wrote that you don't use onclick, because it interferes with another function that is called onclick. If that is the only reason, then please try to prevent the interference as follows.
Change the button as follows:
<input type="button" id="clickbutton" />
Find the $(document).ready(function() { ... }); in your page and add the following code inside:
$("#clickbutton").click(function(e) {
e.stopPropagation();
$("#pform").submit();
});

Have you tried adding a variable to track whether you have already submitted? For example:
<script language="javascript" type="text/javascript">
var formSubmitted = false;
function submitForm() {
if (!formSubmitted){
$("#pform").submit();
formSubmitted = true;
}
}
</script>
<input type="button" onmouseover="submitForm();" />
That should ensure it only happens once (even if submitForm() is getting called many times).

Admiraalit -
I'm trying your last suggestion. This is client side called onmouseover
<script>
function checkLoginStatus() {
jQuery.ajax({
type: "POST",
url: "checkstatus.php",
success: function(res){
if(res == "0") {
alert("Login Required");
}
}
});
}
</script>
and this is checkstatus.php
<?php
session_start();
echo "checking status";
if(isset($_SESSION["username"]))
{
echo "1";
} else {
echo "0";
}
?>
I have verified with an alert box that checkLoginStatus() is being called, but nothing happens otherwise. What is wrong?

This works. I think the problem was the extra echo statement I put in checkstatus.php for testing.
<script>
function checkLoginStatus() {
jQuery.ajax({
type: "POST",
url: "checkstatus.php",
success: function(res){
if(res == "0") {
alert("need to log in");
}
}
});
}
</script>
<?php
session_start();
if(isset($_SESSION["username"]))
{
echo "1";
} else {
echo "0";
}
?>
<?php
session_start();
if(isset($_SESSION["username"]))
{
echo "1";
} else {
echo "0";
}
?>
This provides the not logged in message and I can submit using onmouseout so all is good. Thanks everyone.

Related

How to detect button value change in JQuery?

I've a sign up form which has submit button with value "GET INSTANT ACCESS!" :
<input type="submit" class="wf-button" name="submit" value="GET INSTANT ACCESS!">
After submit, the value gets change to 'Thank You!':
<input type="button" class="wf-button" value="Thank You!">
I need to detect the button value. If it becomes "Thanks You!" then I have to show a popup. And this value gets change by some Ajax (GetResponse form). There is no page refresh.
I've tried below code but it is only working in FireFox & not working in Chrome.
<script>
$(function() {
$(".modalbox").fancybox();
});
$(function() {
$('.wf-button').bind("DOMSubtreeModified",function(){
//if btn valu is 'Thank You! trigger popup'
$(".modalbox").trigger('click');
});
});
</script>
Live URL: http://www.idynbiz.com/web/html/gold_ira_vf/? (just to show how the button changes its value)
Can some one help how can I detect the button value and show my popup? The button change its value in real time (Ajax). There is not page refresh.
Is there any JQuery approach with bind() Or on() function to detect the value?
$(function() {
$('.btn1').on('change', function() {
alert('Do stuff...');
});
$('.lnk1').on('click', function() {
$('.btn1').val('Thank you!');
$('.btn1').trigger('change');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="submit" class="btn1" value="SUBSCRIBE" />
Change button value
OK ,
when button is clicked and form is submitted for saving. just write these code
$(document).ready(function ()
{
$('.wf-button').click(function ()
{
var valueofbutton = $(this).attr('value');
if(valueofbutton == 'Thank You!')
{
window.open(); //// whatever you want to open in popup
}
});
});
i m sure that this will work
You can use the following function in javascript which gets called after any > kind of postback, i.e. synchronous or asynchronous.
function pageLoad()
{
if($(".wf-button").val()=="Thank You!")
{
// show your popup
}
}
Hope it works....

block back button - ignore on click of button

I have a screen where I don't want the user to click on the back button. Now I am doing an ajax call to show that screen. There a button on it, when the click event is fired I want to redirect to the home page. Here its is.
$.post("<?php echo base_url();?>register/citizen", myobj2, function(data){
$("body").empty().append(data);
window.location.hash="no-back-button";
window.location.hash="Again-No-back-button";
window.onhashchange=function(){window.location.hash="no-back-button";}
window.onbeforeunload = function() {
return "If you leave this page you will have to register again.";
}
});
On the page that comes in I have
$(document).ready(function(){
$("#localfinal").unbind('click').on("click", function(){
//$().redirect('<?php //echo base_url();?>');
window.location(<?php echo base_url();?>);
});
});
When the user clicks the button, I get the message about leaving the page. Instead I just want to redirect to the base url (home);
Any ideas ?
Reset onbeforeunload handler, btw, i don't think you need to unbind() click handler:
$("#localfinal").on("click", function(){
window.onbeforeunload = $.noop;
window.location(<?php echo base_url();?>);
});
Try this
<SCRIPT type="text/javascript">
window.history.forward();
function noBack() { window.history.forward(); }
</SCRIPT>
</HEAD>
<BODY onload="noBack();"
onpageshow="if (event.persisted) noBack();" onunload="">

disable button with timeout

I have this form with conditions that alert validation errors before posting data. the problem is if someone double clicks (by mistake perhaps), the form is submitted, then the form is cleared on the first click then the second click will alert 'form empty', which could be confusing as it all happens in a split second. so what I want is to temporarily disable the button when clicked for 3 seconds. but what I have now just times out the whole function for 3 seconds not just disabling the button. how should I be doing this? here is a simplified version of the form. Thanks
$('#send').click(function(){
var self = $('#send');
setTimeout(function() {
self.disabled = false;
if(!$('#text').val()){
alert('field empty');
}else{
$('#message').html('done');
$('#text').val('');
}
}, 3000);
});
I've written a small example for you, of disabling a button on click. The timeout will enable the button after 3000 miliseconds.
Working demo
html:
<input id="text">
<input id="send" type="button" value="send"/>
<div id="message"></div>
Javascript:
$('#send').click(function(){
var button = $(this);
button.attr('disabled', 'disabled');
setTimeout(function() {
button.removeAttr('disabled');
},3000);
if(!$('#text').val()){
alert('field empty');
button.removeAttr('disabled');
}else{
$('#message').html('done');
$('#text').val('');
}
});
You could use jQuery's one() instead of click(). Once the function is run it will be unbound.
If you want to re-enable it you could put the timeout to re-bind it at the end of the function.
Using your method, it looks like you're never actually disabling the button:
this.disabled = 'disabled';
You are not correctly disabling the button. You are setting the .disabled property on a jQuery object, not the wrapped DOM element.
Try:
self.prop('disabled', false);
Instead of:
self.disabled = false;
EDIT:
Actually the code above was attempting to re-ebable the button. There was no code to disable the button.
I also think you want to perform the validation right away. The call to setTimeout() should just be for re-enabling the button, like this:
$('#send').click(function() {
var self = $(this);
// Disable the button.
self.prop('disabled', true);
// Process click.
if (!$('#text').val()) {
alert('field empty');
} else {
$('#message').html('done');
$('#text').val('');
}
// Cause the button to re-enable after 3 seconds.
setTimeout(function() {
self.prop('disabled', false);
}, 3000);
});

wierd error : code get executed more than once per click

i have a like comments system
when i click on the like link sometimes it works fine but some times it sends up to 8-9 request per click ! i have the same problem on another jquery code which works with keydown event
<a href="javascript:void(0);" class="like_comment" ><?php echo $likeLable; ?></a>
$('.like_comment').live('click', function () {
var parent = $(this).parent();
var comment_id = parent.parent().find('.comment_id').val();
parent.fadeOut(200);
$.post("<?php echo base_url(); ?>album/like", {
comment_id: comment_id
},
function (data) {
if ($.trim(data) == 'ok') {
var like_span = parent.parent().find('.like_counter');
var like = parseInt(like_span.text()) + 1;
like_span.text(like);
parent.html('<a href="javascript:void(0);" class="unlike_comment" ><?php echo $unlikeLable; ?></a>');
parent.fadeIn(200);
return false;
} else {
parent.fadeIn(200);
alert(data);
}
})
})
is there anything wrong with this code ?
Try returning true from the event handler to signify that you handled the event. That way noone else will pick it up...
If that doesn't work, then you are probably registering multiple event listeners for the same event. Use your favorite debugger to pause javascript execution, then use the console to inspect all the event listeners on the relevant dom elements.
Its hard to know without seeing the rest of your code and know what element the click is applied to, so one of the following 3 solutions could work:
$('.like_comment').on('click',function(e) {
//do something
e.preventDefault(); // stops default button action, e.g. submitting a form
e.stopPropagation(); // stops event bubbling back to parent element
}
return false; /// stops default link action
});
Also as a by-the-way, live is now deprecated and has been replaced by "on" instead.

Is there a way to check if a postback is in progress?

In the case that a button is clicked multiple times on a page - Is there a way to figure out using javascript/jquery that a postback is already in progress and cancels the new attempt to submit the page?
Thanks
You can avoid users from double clicking by disabling whatever form elements can cause a form submit.
Checkout http://greatwebguy.com/programming/dom/prevent-double-submit-with-jquery/ for an example.
You can disable the button on first click, so that you could not click it when the post is in progress, and re enable it when the post-back has finished.
<script type="text/javascript" language="JavaScript">
var submitted = false;
function SubmitTheForm() {
if(submitted == true) { return; }
document.myform.submit();
document.myform.mybutton.value = 'Thank You!';
document.myform.mybutton.disabled = true;
submitted = true;
}
</script>
<form method="post" action="#">
<input type="submit" onclick=return SubmitTheForm()>
</form>
you could always just disable the button in the onclick handler.
$('input[type="submit"]').click(function(e) {
e.preventDefault();
var self = this;
$(self).attr('disabled', 'disabled');
$.post('url',$(self).closest('form').serialize(), function() {
$(self).removeAttr('disabled'); // re-enable after request complete.
});
});
You could have your click event set a variable in your click handler to true and only allow the handler to proceed when the value is false. Of course you will have to set it to false again when your callback finishes.
if (!processInProgress) {
processInProgress = 1
// start the process
}

Categories

Resources