jQuery: Cannot change style of element after selected - javascript

Here is my code. Where you see "alert([...]);", an alert pops up. Why doesn't the CSS style change? The 'click' event doesn't fire either!
resolveSideMenuAddress: function () {
var firstLink = $("#masterHeaderMenu .masterHeaderMenuButton a:first");
function select(link) {
alert('i alert');
link.css({
'color': '#9a4d9e',
'cursor': 'default'
});
alert('color and cursor not changed');
link.click(function () {
alert('click');
return false;
});
}
if (window.location.pathname === firstLink.attr('href')) {
alert('i alert');
select(firstLink);
}
}
I've tried addClass() and can't change the color of the link that way either.

First, you're not actually firing the click event, but rather applying a click handler to the link. It won't fire until you actually click the link. If you want existing click handlers to be run you can try link.click() (without the function). If you want the link to actually be taken, you should simply set the location to the value of the link's href attribute. Second, I'm not sure why the CSS isn't being applied properly. It looks ok to me. I'd suggest using Firefox/Firebug and inspecting the element after the function has run to see what styles are actually in use.

try using $(link) instead of just link
like this:
resolveSideMenuAddress: function () {
var firstLink = $("#masterHeaderMenu .masterHeaderMenuButton a:first");
function select(link) {
alert('i alert');
$(link).css({
'color': '#9a4d9e',
'cursor': 'default'
});
alert('color and cursor not changed');
$(link).click(function () {
alert('click');
return false;
});
}
if (window.location.pathname === firstLink.attr('href')) {
alert('i alert');
select(firstLink);
}
}

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 not logging event or performing function

$('.logoTop').on('click', 'img', function (event) {
console.log(event);
if ($(".navTop").css("top", "-100px")) {
$(".navTop").css("top", "0px");
}
else{
$(".navTop").css("top", "-100px")
}
});
This is my code, where .logoTop is an image, but when I click on it, nothing happens and the console does not even log an event.
Edit: The function is contained within the $(document).ready() and other functions are working properly.
Note: I use other jQuery functions to add and remove class names before this function.
If .logoTop is the class of the image it will never fire, because you are basically saying this :
In the element with a class name logoTop find an image and wait for the click event.
There is no image inside your image tag, so your code should be like this
$('body').on('click', '.logoTop', function (event) {
console.log(event);
if ($(".navTop").css("top", "-100px")) {
$(".navTop").css("top", "0px");
}
else{
$(".navTop").css("top", "-100px")
}
});
Or simply (Note that the first example will work for dynamically created elements)
$('.logoTop').on('click', function (event) {
console.log(event);
if ($(".navTop").css("top", "-100px")) {
$(".navTop").css("top", "0px");
}
else{
$(".navTop").css("top", "-100px")
}
});

click event not working when changing id or class

I'm starting with jquery, and have an issue here:
http://jsfiddle.net/8guzD/
$('#test.off').click(function(){
$(this).removeClass('off').addClass('on');
});
$('#test.on').click(function(){
$(this).removeClass('on').addClass('off');
alert('ok');
});
the first part of the code goes well, the class is apply, but when I attach an event in this element with its new class it won't work.
Can someone explain me what is the problem exactly?
I tried with javascript,
http://jsfiddle.net/R5NRz/
var element = document.getElementById('test');
element.addEventListener('click', function() {
this.id ='test2';
alert("ok");
}, false);
var element2 = document.getElementById('test2');
element2.addEventListener('click', function() {
alert("ok2");
}, false);
and it didn't really help me, having the same issue
try
$(document).on("click",'#test.on',function(){
$(this).removeClass('off').addClass('on');
alert('ok');
});
$(document).on("click",'#test.off',function(){
$(this).removeClass('off').addClass('on');
alert('ok passs');
});
Demo
In your jQuery example you are binding to DOM elements that exist at that time. That is why you see the first fire but not the second. It is not a match for your '#test.on' selector when the code is run. What you want to do instead is use delegation:
$('#test').on('click',function() {
var ele = $(this);
if (ele.hasClass('on')) {
ele.removeClass('on').addClass('off');
} else {
ele.removeClass('off').addClass('on');
}
});
This assumes that you are doing more than just toggling classes. If you want simply toggle classes then an easier solution is to pick one as the default and use the other as a flag. For example, .on is on but without .on it's off. Then you can just use toggle:
$('#test').on('click', function() {
$(this).toggleClass('on');
});
$("#test.on")
Doesn't bind to anything. Try this:
$('#test').click(function() {
if($(this)).hasClass('off') $(this).removeClass('off').addClass('on');
else $(this).removeClass('on').addClass('off');
});
You might consider using an 'active' class instead and just toggling that, instead of have two separate on/off classes. Then you can write:
$("#test").click(function() {
$(this).toggleClass('active');
});

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

jQuery, Triggering event from Class

Please take a look at the following code and fiddle.
CODE
$("#enable").click(function(e) {
if (!$("#enable").data('isOn')) {
$("#holder").find('.clickable').each(function(d) {
$(this).css('border', '1px solid red');
$(this).addClass('clickEnabled');
});
$("#enable").data('isOn', true);
} else {
$("#holder").find('.clickable').each(function(d) {
$(this).css('border', '');
$(this).removeClass('clickEnabled');
});
$("#enable").data('isOn', false);
}
});
$(".clickEnabled").click(function(e) {
alert('clicked');
});
Fiddle: http://jsfiddle.net/qAuwt/
I am basically trying to toggle a "clickEnabled" class on elements when a button is pressed. The toggling is working as the border is changing however the clickEnabled class is not responding to click events
There are no .clickEnabled elements when you set the event handler. You can still catch the click event, though:
$(document).on("click", ".clickEnabled", function(){
alert("Hello, world!");
});​
Change:
$(".clickEnabled").click(function (e) {
alert('clicked');
});
To:
$(".clickable").click(function (e) {
if ( $(this).hasClass("clickEnabled") )
{
alert('clicked');
}
});
As #araxanas mentioned, the .clickEnabled don't exist on load. So I switched the selector to .clickable, which do. However, you only want to handle the click when they're enabled. That's why I've added the conditional. It'll only alert if the clicked element has the clickEnabled class.
Also, it might help to move the css out of javascript, that way you can see visually if the class is there or not, see my updated fiddle.
The problem is that when page loaded, the click event handler binds to no elements (because there is no element with class 'clickEnabled').
The solution is to change the .click() method to .live() method:
$(".clickEnabled").live('click', function (e) {
alert('clicked');
});

Categories

Resources