Why js event disappear? - javascript

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");
});
});
});

Related

JS - use preventDefault instead of return false

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

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?

Disabling and enabling click event on image...jquery

what would be the best way to enable and then re-enable and image click with jquery?
I can diasble the click event easy enough
$(document).on("click", "#rightPager", function () {
if (condition) {
$(this).click(false);
}
});
how would I go about in 'enabling' the click event again based on a certain condition?.
I would want to enable the button again for example
$(document).on("click", "#leftPager", function () {
$("#rightPager").click(true);
});
In order to rebind you would need to use the original .on("click") event again.
Write a function to bind an event to your image:
function bindImage() {
$(img).on("click", function() {
// Your bind event goes here
});
}
Then write a conditional to unbind the event on the image if your condition returns true, then if its false, rebind the event to the image as normal.
if (condition) {
$(img).unbind();
} else {
bindImage();
}
Alternatively, you could complete this within a single function such as:
$(document).on("click", "#rightPager", function () {
if (condition) {
// terminate the function
return false;
} else {
// put your function here to run as normal
}
});
Try to use jQuery off method.
JSFiddle
$(document).off('click', '#rightPager');
Full code:
var condition = true;
$(document).on("click", "#rightPager", function () {
if(condition){
alert('Click was disabled');
$(document).off('click', '#rightPager');
}
});
you disable the default event by:
$(document).click(function(e) {
e.preventDefault();
condition ? doSomething() : doSomethingElse();
});​
so basically is not that you enable then disable, you prevent the default action, check for your condition and they execute appropriate function

Jquery - Differentiate between 'click' and 'focus' on same input when using both

I'm trying to trigger an event on an input if the input is clicked or if the input comes in to focus.
The issue i'm having is preventing the event from firing twice on the click as, obviously, clicking on the input also puts it in focus. I've put a very loose version of this on jfiddle to show you what I mean, code as below:
HTML:
<body>
<input type="textbox" name="tb1" class="input1"></input>
<label> box 1 </label>
<input type="textbox" name="tb2" class="input2"></input>
<label> box 2 </label>
</body>
JQuery
$(function () {
$('.input2').click(function() {
alert("click");
});
$('.input2').focus(function() {
alert("focus");
});
});
JSFiddle: http://jsfiddle.net/XALSn/2/
You'll see that when you tab to input2 you get one alert, but if you click you get two. Ideally for my scenario, it needs to be one alert and ignore the other. it also doesn't seem to actually focus.
Thanks in advance for any advice.
How about setting a flag on focus so we can fire on focus and ignore clicks but then listen for clicks on the focussed element too? Make sense? Take a look at the demo jsFiddle - If you focus or click on the unfocussed .index2 it triggers the focus event and ignores the click. Whilst in focus, clicking on it will trigger the click.
I have no idea why you would want this (I cant imagine anyone wanting to click on a focussed element for any reason (because the carat is already active in the field) but here you go:
$(function () {
$('.input2').on("click focus blur", function(e) {
e.stopPropagation();
if(e.type=="click"){
if($(this).data("justfocussed")){
$(this).data("justfocussed",false);
} else {
//I have been clicked on whilst in focus
console.log("click");
}
} else if(e.type=="focus"){
//I have been focussed on (either by clicking on whilst blurred or by tabbing to)
console.log("focus");
$(this).data("justfocussed",true);
} else {
//I no longer have focus
console.log("blur");
$(this).data("justfocussed",false);
}
});
});
http://jsfiddle.net/XALSn/12/
This probably won't be the best answer, but this is a way of doing it. I would suggest adding tab indexes to your inputs and firing the focus event when you blur from another input.
I've added that to this fiddle:
http://jsfiddle.net/XALSn/9/
$(function () {
$('.input2').click(function(e) {
alert("click");
e.preventDefault();
});
});
$('input').blur(function(){
$('input').focus(function() {
alert("focus");
});
});
You can use one thing I am using very often in JS
var doSomething = true;
$(function () {
$('.input2').click(function(e) {
if (doSomething) {
// do something :)
}
doSomething = false;
});
$('.input2').focus(function() {
if (doSomething) {
// do something :)
}
doSomething = false;
});
});
But You have to change value of doSomething on mouseout or foucs over etc. :)
$(function () {
var hasFocus = false;
$("body")
.off()
.on({
click : function()
{
if(!hasFocus)
{
hasFocus = true;
alert("click");
}
},
focus : function()
{
if(!hasFocus)
{
hasFocus = true;
alert("focus");
}
}
},".input2");
});
try setting a flag hasFocus and act accordingly
http://jsfiddle.net/AEVTQ/2/
just add e.preventDefault() on the click event
$(function () {
$('.input2').click(function(e) {
console.log("click");
e.preventDefault();
e.stopPropagation();
});
$('.input2').focus(function() {
console.log("focus");
});
});
If I understand your question right, the e.prevnetDefault() will prevent the browser from automatically focusing on click. Then you can do something different with the click than would with the focus

html div onclick event

I have one html div on my jsp page, on that i have put one anchor tag, please find code below for that,
<div class="expandable-panel-heading">
<h2>
<a id="ancherComplaint" href="#addComplaint"
onclick="markActiveLink(this);">ABC</a>
</h2>
</div>
js code
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
function markActiveLink(el) {
alert($(el).attr("id"));
}
here I when I click on div I got alert with 123 message, its fine but when I click on ABC I want message I want to call markActiveLink method.
JSFiddle
what is wrong with my code? please help me out.
The problem was that clicking the anchor still triggered a click in your <div>. That's called "event bubbling".
In fact, there are multiple solutions:
Checking in the DIV click event handler whether the actual target element was the anchor
→ jsFiddle
$('.expandable-panel-heading').click(function (evt) {
if (evt.target.tagName != "A") {
alert('123');
}
// Also possible if conditions:
// - evt.target.id != "ancherComplaint"
// - !$(evt.target).is("#ancherComplaint")
});
$("#ancherComplaint").click(function () {
alert($(this).attr("id"));
});
Stopping the event propagation from the anchor click listener
→ jsFiddle
$("#ancherComplaint").click(function (evt) {
evt.stopPropagation();
alert($(this).attr("id"));
});
As you may have noticed, I have removed the following selector part from my examples:
:not(#ancherComplaint)
This was unnecessary because there is no element with the class .expandable-panel-heading which also have #ancherComplaint as its ID.
I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.
Try this
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
$('#ancherComplaint').click(function (event) {
alert($(this).attr("id"));
event.stopPropagation()
})
DEMO
Try following :
$('.expandable-panel-heading').click(function (e) {
if(e.target.nodeName == 'A'){
markActiveLink(e.target)
return;
}else{
alert('123');
}
});
function markActiveLink(el) {
alert($(el).attr("id"));
}
Here is the working demo : http://jsfiddle.net/JVrNc/4/
Change your jQuery code with this. It will alert the id of the a.
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
markActiveLink();
alert('123');
});
function markActiveLink(el) {
var el = $('a').attr("id")
alert(el);
}
Demo
You need to read up on event bubbling and for sure remove inline event handling if you have jQuery anyway
Test the click on the div and examine the target
Live Demo
$(".expandable-panel-heading").on("click",function (e) {
if (e.target.id =="ancherComplaint") { // or test the tag
e.preventDefault(); // or e.stopPropagation()
markActiveLink(e.target);
}
else alert('123');
});
function markActiveLink(el) {
alert(el.id);
}
I would have used stopPropagation like this:
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
$('#ancherComplaint').on('click',function(e){
e.stopPropagation();
alert('hiiiiiiiiii');
});
Try out this example, the onclick is still called from your HTML, and event bubbling is stopped.
<div class="expandable-panel-heading">
<h2>
<a id="ancherComplaint" href="#addComplaint" onclick="markActiveLink(this);event.stopPropagation();">ABC</a>
</h2>
</div>
http://jsfiddle.net/NXML7/1/
put your jquery function inside ready function for call click event:
$(document).ready(function() {
$("#ancherComplaint").click(function () {
alert($(this).attr("id"));
});
});
when click on div alert key
$(document).delegate(".searchbtn", "click", function() {
var key=$.trim($('#txtkey').val());
alert(key);
});

Categories

Resources