JS - use preventDefault instead of return false - javascript

Not great with Js so looking for some help with some existing code.
I have the following anchor
<span>Add</span>
I am getting a warning regarding the 'onclick' event where its telling me that i dont have keyboard equivilant handler for the the onclick="return false; I have done some research and i can prevent this warning by using preventDefault. if i put this in a script tag in the page then it works the same and i think it will get rid of the issue.
$("a.addrom").click(function(e) {
e.preventDefault();
});
However, i would prefer to add it to the existing js but im having a hard time working out whats going on. I am trying to add it to the click event.
setupRooms: function (settings) {
//hide all age fields
$(settings.agesSelector, settings.hotelSearchDiv).hide();
//hide all except first
$(settings.roomsSelector + ":not(:first)", settings.hotelSearchDiv).hide();
$('select', settings.hotelSearchDiv).prop('selectedIndex', 0); //set all to 0
$(settings.addRoomSelector, settings.hotelSearchDiv).on('click', function () {
methods.addRoom(settings);
});
$(settings.removeRoomSelector, settings.hotelSearchDiv).on('click', function () {
var id = $(this).data('id');
methods.removeLastRoom(settings, id);
});
$(settings.childrenNumberSelector, settings.hotelSearchDiv).on('change', function () {
methods.handleChildrenChange(settings, $(this));
});
},
Edit* This code worked for me thanks to #patrick & #roberto
$(settings.addRoomSelector, settings.hotelSearchDiv).on('click', function (e) {
e.preventDefault();
methods.addRoom(settings);
});

If i understood correctly you want to add that on your click handlers:
$(settings.addRoomSelector, settings.hotelSearchDiv).on('click', function (e) {
e.preventDefault();
methods.addRoom(settings);
});
$(settings.removeRoomSelector, settings.hotelSearchDiv).on('click', function (e) {
e.preventDefault();
var id = $(this).data('id');
methods.removeLastRoom(settings, id);
});
Should be enough for having the prevent default in your click handlers.
Cheers

Related

How to fire onClick function of a div depending on another div

I want to call a function on one type of button click on my HTML page.
I have got around 10 such button on the page and wrote the below code to call a function when the button is clicked,
$('.divname').each(function (index) {
$(this).on("click", function (e) {
//Call Another Function
});
});
And this is working fine as expected.
However the issue is, sometimes depending on some condition one dynamically generated div is been created(Pop up message) and I dont want my above said code to work when the pop up message comes up.
Could you please advise how this can be achieved.
Thanks and Regards,
Aniket
Hi What something like set a bool and check if it true or false...somthing like:
var enable = true;
$('.divname').each(function (index) {
$(this).on("click", function (e) {
//Call Another Function
if(!enable) return;
});
});
//set it to false on popup show (or something else event)
$(popup).show(function(){
enable = false;
})
In simplest way.
$('.divname').each(function (index) {
$(this).on("click", function (e) {
//Simply check the condition for that Open Pop up message
if(openPopUp){
return;
}
callfunction();
});
});
try something,
$('.divname').each(function (index) {
$(this).on("click", function (e) {
if($('#popupModal:visible').length == 0){ // check length of visible modals
//Call Another Function
}
});
});

jquery onblur not firing

I am trying to get an onblur/onfocus combination working for a pair of text boxes which I am selecting via class in jquery. I am not getting any errors in debug, but the blur function never seems to be called. When debugging my breakpoint in the blur function is not hit.
$(document).ready(function () {
var row = $(this).closest('tr');
$('.editClass').click(function () {
var editBoxes = $(row).find('.editClass');
var focus = 0;
$(editBoxes).focus(function () { focus++ });
$(editBoxes).blur(function () {
focus--;
setTimeout(function () {
if (!focus) {
alert('LOST FOCUS'); // both lost focus
}
}, 50);
});
});
});
Pretty sure the problem here was that the editBoxes were dynamically added to the page. This was not apparent in my question. Since they were dyncamically added I need to use
$(document).on('blur', '.editBoxes', function (){
...
}
The last two lines of your code example should be this
});
});
This is needed for closing the ready and click function call.
Another possible problem is that you wrap the focus and blur listeners in a click handlers. Why did you do this?

prevent jQuery post request executed twice by double click

I've searched for equal questions, but found not a single one for my specific case.
I have an element
<span id="myButton">Click</span>
and a jQuery post-request bound to it
$(document).ready( function()
{
$(document).on( 'click', '#myButton', function(e)
{
$.post( "RESPONDING_WEBPAGE_HERE.php" ).done( function( result )
{
console.log( result );
});
});
});
Now, for every time you click the button, it makes a post-request. Makes sense. What I want is a good solution for only executing the post-request, if the result function (.done()) is executed.
For sure, I know to handle that with a variable like var isAjaxRequest = false; setting it to true, and back to false in the resulting function, but maybe there is a better (jQuery build-in) way of doing it.
Here is my solution by now. I would be really great if there are better ones.
var isAjaxRequest = false;
$(document).ready( function()
{
$(document).on( 'click', '#myButton', function(e)
{
if( !isAjaxRequest )
{
isAjaxRequest = true;
$.post( "RESPONDING_WEBPAGE_HERE.php" ).done( function( result )
{
isAjaxRequest = false;
console.log( result );
});
}
});
});
Thank you =)
I commonly set the button to disabled when it is clicked and then remove the disabled attribute on the callbacks for the POST request.
$(document).on('click', '#button', function () {
$('#button').attr('disabled', true);
$.post('something').done(function () {
$('#button').removeAttr('disabled');
}).fail(function () {
$('#button').removeAttr('disabled');
});
});
This will prevent the button from being clicked again once it has already been clicked.
As per the comments; If you want this behaviour on a span element or others which don't allow the disabled attribute, you could set a class when clicked.
$(document).on('click', 'span#button:not(.disabled)', function () {
$(this).addClass('disabled');
$.post('something').done(function () {
$(this).removeClass('disabled');
}).fail(function () {
$(this).removeClass('disabled');
});
});
The above code will make sure the element can only be clicked if it doesn't have the disabled class. This will also work for the button elements so there is no need to duplicate code for both methods.
I like to use .one() to attach the event handler and re-attach the event after the ajax call is complete. This will handle all cases even when your target doesn't support disabling:
//define handler function
var myButtonHandler = function(e) {
$.post("RESPONDING_WEBPAGE_HERE.php").done(function() {
attachButtonHandler("#mybutton"); //re-attach the click event after AJAX complete
});
}
//attach an event handler that's only good for one click
function attachButtonHandler(selector) {
$(document).one('click', selector, myButtonHandler);
}
//on doc ready, attach the event handler for the first time
$(function() {
attachButtonHandler("#mybutton");
});

Why js event disappear?

I am using this code to add click event to elements with some class:
jQuery(document).ready(function () {
jQuery(".myclass").each(function (index, value) {
jQuery(this).click(function (e) {
e.preventDefault();
console.log("asd");
});
});
// breakpoint
)};
When the breakpoin is hit in firebug, I check click events of first myclass element in console and it has this event. When I click continue (in firebug) and the site finish to load, I check it again and it has no click event. Can you tell me why this event disappear?
Can't really replicate an issue with the code you've posted, however you don't need to do a loop to add your event handling.
you can just:
jQuery(".myclass").click(function (e) {
e.preventDefault();
player.onclick();
});
You'd also only need to pass through the event e, and prevent it if you are clicking on a a tag, input type='submit' etc
UPDATE: the reason your code is failing though, is because you have a syntax error, your } and ) are the wrogn way round. try
jQuery(document).ready(function () {
jQuery(".myclass").each(function (index, value) {
jQuery(this).click(function (e) {
e.preventDefault();
console.log("asd");
});
});
});

jQuery Dual Range Slider Reload

I want to build an dual range slider in jQuery by my own.
My first attempt kind of works. But sometimes if I release the mouse button after dragging a slide the website automatically reloads.
I've uploaded my Code on jsfiddle:
http://jsfiddle.net/u2d8P
Here is the js part:
$(document).ready(function () {
var $dragging = null;
$('.slider').bind("mousemove", function(e) {
if ($dragging) {
if (e.pageX<200) {
$dragging.offset({
left: e.pageX
});
}
}
});
$('.left_slider').bind("mousedown", function (e) {
$dragging = $(e.target);
});
$('.right_slider').bind("mousedown", function (e) {
$dragging = $(e.target);
});
$('.slider').bind("mouseup", function (e) {
$dragging = null;
});
});
Even in the fiddle it reloads sometimes after releasing the mouse button.
What am I doing wrong?
Thanks in advance for your help!
Greetz
Since your anchors (do they even need to be anchors?) have no href value (which is invalid, btw), the default action is to reload the current page. You'd need to either use preventDefault to stop that, or use a value such as # or javascript:void(0).
http://jsfiddle.net/isherwood/u2d8P/1/
Here's how you'd do it using preventDefault. Credit to Joe Cullinan.
http://jsfiddle.net/hPkS6

Categories

Resources