"#button_1" isn't affected by .click() or .hover() - javascript

Probably a rookie mistake, but my #button_1 ID isn't affected by the click() or hover() jQuery effects.
If someone could take a quick look at my JSFiddle, it would be greatly appreciated.
It's probably pretty obvious, but I want #button_1 to act as every other button. :)
Again, I suspect it's a pretty stupid mistake, something that I've overlooked.

Don't repeat so much code , try this and its working
Try line by line , its throwing error in somewhere in the code and breaking the bind events.
you have some error in hover or so , remove everything and have bind events, they are work.
You know this right ,when line 1 breaks in documentready , all bindings below may not get binded.
$(document).ready( function () {
$('#button_1,#button_2').click(function() {
alert('Handler for .click() called.');
});
});

Might I suggest condensing that code a little, to something closer to:
$('a div[class^="button"]').click(
function(e){
e.stopPropagation(); // prevent the click bubbling to the parent 'a' element
$('.button_active')
.removeClass('button_active')
.addClass('button_normal');
$(this).addClass('button_active').removeClass('button_normal');
});
JS Fiddle demo.
Edited in response to question from the OP:
Just to add, [the Fiddle updated by the OP to include the above code] actually sets "button_hover" as the class instead of "button_active", any idea why that would be?
Yep; that's in response to the specificity of the CSS selectors, I add and remove classes as needed in response events (rather than repeatedly checking for whether or not button_hover is set). As the element ends up with class="button_normal button_hover", and the order of the css (I think) places greater emphasis on the later-declared class, button_hover is maintained. It's late, and I'm a bit tired, but that's sort of (in a nutshell) what's happening.
The following demo incorporates everything (I think) that you need, and, coupled with revised CSS selectors, should do as you want:
$('a div[class^="button"]').hover(
function(){
$(this).addClass('button_hover').click(
function(e){
e.preventDefault();
$('.button_active')
.addClass('button_normal')
.removeClass('button_active');
$(this).addClass('button_active').removeClass('button_hover');
});
},
function(){
$(this).removeClass('button_hover');
});
CSS:
.button_active,
.button_normal.button_active { background: #000; }
.button_normal.button_hover { background: #ff0; }
.button_normal { background: #d89; }
JS Fiddle demo.
References:
attribute-begins-with (^=) selector.
e.stopPropagation().
removeClass().
addClass().

Related

.removeClass not working, and preventing .addClass from working

I'm having a hard time finding any information that helps with this issue. I've tried several other options that worked for other people on here, but it doesn't seem to be working.
I have a div set up like this:
<div class="dynamic-content">
<div class="button"></div>
<div class="content"></div>
</div>
What I'm trying to do is apply a CSS animation to .dynamic-content when .button is clicked, by adding a specific class, and then removing that animation by clicking .button again and removing the specific class.
Here is my jQuery:
$(".button").on('click', function() {
if ($(".dynamic-content").hasClass('open')) {
$(".dynamic-content").removeClass('open'));
} else {
$(".dynamic-content").addClass('open'));
}
}
If I don't include the .removeClass() part, the addClass works perfectly. However, as soon as I put in the .removeClass, in the inspector, I can see .dynamic-content lighting up, as if targeted and acted on by JS, but nothing happens, not even .addClass is working.
That is because you have error in your code at line:
$(".dynamic-content").removeClass('open'));
//^Remove extra brace
Remove extra spaces and you are good to go.
You can also optimize your code by using .toggleClass():
$(".button").on('click', function() {
$(".dynamic-content").toggleClass('open');
});
JS:
$(".button").on('click', function() {
if ($(".dynamic-content").hasClass('open')) {
$(".dynamic-content").removeClass('open');
} else {
$(".dynamic-content").addClass('open');
}
});
Does the conditional work? Because ".dynamic-content" is a class, jQuery will get the first one it finds. Maybe there's another one on the page, which plays with your condition?
Another thing that may happen, as people have said, is that your extra ")" is breaking your function.
Either way, I would try toggleClass instead, it does exactly what your condition does:
$(".button").on('click', function() {
$(".dynamic-content").toggleClass("open")
}
If the class is there, it removes it, if not, it adds it.

Can't change position when code works with background-color

I want to affect the position of any item on my page when it is clicked. How can i do this without using id names? I have a working piece of code which works when changing background-color but doesn't seem to want to work when i change it to position.
$(document).click(function(event) {
$(event.target).css({'background-color': 'blue'});
});
Any help always appreciated. Thanks
Try to delegate the event in order to target more precisely the element, but want You are trying to achieve could cause really bad performance issues.
Try this:
$(document).on('click', '*', function(event) {
$(this).css({'position': 'relative'});
});

jQuery code doesn't work on Google Chrome?

This code doesn't work on google chroome but works on Firefox, opera, and IE
function show() {
$('#networks').click(function () {
$('#social').slideDown(1000);
$('#face,#twitter,#google,#youtube,#rss').fadeIn(2000)
});
$('#networks').blur(function () {
$('#face,#twitter,#google,#youtube,#rss').fadeOut(1000);
$('#social').delay(1000).slideUp(1000);
});
}
at the same documents after this code i wrote the code below and work on google chroome and all other browsers, why this code works well in google chroome but above doesn't ???
function UseData() {
$("#submit").click(function () {
$(this).val("");
$(this).animate({
width: '250px',
}, "slow")
});
$("#submit").blur(function () {
$(this).val("Search");
$(this).animate({
width: '175px',
}, "slow");
});
}
thanks
http://jsfiddle.net/A4CJz/10/
I believe the effect you want is this:
when the mouse hovers over the element (not focus) then show the social menu
when the mouse leaves the element (not blur) then hide the social menu
Your markup was atrocious. That's why it wasn't working in chrome. You really need to learn valid markup and valid JS before this solution will be helpful. In particular, you cannot wrap an a tag around an li tag in a list. The only valid child of ul is li.
You also don't need to id each of the li elements and target them directly. A quick lesson in jquery will show you that you can target by the tag name, which you will see me do in the example fiddle I posted, as such: $('#social li')
I also did away with your inline JS and used jquery to wire up the mouseenter and mouseleave events.
I recommend you study the code carefully and try to understand how and why I restructured your code the way I did.
Okay, at the first your fiddle depends on jQuery so you've to include it. The second thing is that you've to load your script in the head to work with inline-code. (onclick-handlers on html-tags). Otherwise your function 'll be undefined ;-)
But to point out what your real problem is, there's nothing special needed. An a-tag cannot handle focus or blur-events.
You can read more here: http://api.jquery.com/focus/#entry-longdesc
The working fiddle:
http://fiddle.jshell.net/A4CJz/3/
Another tip, prevent the default action of your attached event, to kill its normal behaviour. Simply done with preventDefault on the event-object or an simple return false at the end of your event-handler function.
Update
http://fiddle.jshell.net/A4CJz/12/

jquery - why do i need live() in this situation?

I have a somewhat odd situation. I understand the premise of the live() and bind() functions, yet in a situation where i believe i dont need them, i seemingly do. I will explain.
I made an autosuggest in jquery. I included autosuggest.js at the top of my page. I then have an input field.
The basis of the JS works around:
$(".autosuggest").keyup(function()
{
}
This works - on keyup, my function executes etc as expected - i dont need to use live() or bind() as the input field is on the page from the get go...
Now.. I have also made a 'star rater' esque script.
I have various elements (which are styled), and on hover they are restyled...
$('.rating li').mouseover(function() {
}
does NOT work, YET
$('.rating li').live('mouseover',function() {
}
DOES.
Why do i need to use 'live' in this situation, when i dont in the case of the autosuggest?
Thanks
The only thing I can imagine that would cause this is a lack of a domready event. This should work:
$(function () {
$('.rating li').mouseover(function() {
}
});
the .ratings li isn't parsed yet when you have .mouseover() not working.
You can wrap it in $(document).ready(function() {...}); or use .live() (which creates the binding for any currently parsed at that point in the script and any elements added in the future).
Did you put $('.rating li').mouseover(function() {
}
in $(document).ready(function() {....} ?
Even if you include a .js file, if the elements in the page ('rating li') are not loaded, the bind will not be made.
Without seeing more of you code, it's difficult to say for sure. But my guess would be that your script is running before the pageload completes. try wrapping your bindings (and anything else that depends on particular dom elements to exist) with a call to $(document).ready(...).
something like this:
$(document).ready( function() {
$('.rating li').mouseover(function() {
// whatever
});
$(".autosuggest").keyup(function() {
// whatever else
});
});
If that's not it, then post more of your code, and we'll dig in further.
good luck.

:hover selector doesn't work with jQuery 1.4

Googled about it - found nothing.
I'm talking about CSS :hover, not jQuery .hover().
So, the code:
$('#something a:hover').css({'something': 'thomesing'});
works fine with 1.3, but not with 1.4. How to fix it?
Follow the rules
This is a superb example of why we must always code according to the documentation, and not according to the possibilities. Hacks, or mere oversights like this, will eventually be weeded out.
The proper jQuery (plain css is better) way to do this follows:
$("#something a").hover(
function() {
// $(this).addClass("hovered");
$(this).css("color", "red");
},
function() {
// $(this).removeClass("hovered");
$(this).css("color", "black");
}
);
The $.fn.hover method takes up to two arguments and serves as syntactic sugar for more explicit pointer (mouse) events. In fact, the hover method in jQuery 2.1.0 was nothing but this:
function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
Understand your code, and be concise
As you can see, the fnOver function is called when you enter the element, and again when you exit (if no other method is provided). With this understanding, we can setup simpler instructions:
$("#something a").hover(function () {
$(this).toggleClass("hovered");
});
Native almost always wins
Ultimately, vanilla CSS is the way to go. The :hover pseudo-class has been around for a long time, and works with targeting not only the element to which it belongs, but nested elements as well:
#something a:hover {
background: red;
}
#something a:hover .icon {
animation: 2s rotate ease-out;
}
With something as broadly-supported as :hover, I can think of no good reason to avoid it.
:hover is not a documented pseudoclass selector.
Try this:
$('#something a').hover(function(){
$(this).css({'something': 'thomesing'});
},
function(){
$(this).css({'something': 'previous'});
});
Although, you'd be better to use CSS classes:
$('#something a').hover(function(){
$(this).toggleClass("over").toggleClass("out");
},
function(){
$(this).toggleClass("over").toggleClass("out");
});
http://docs.jquery.com/Events/hover
EDIT:
In respose to BlueRaja's comment below, the following would be more suitable:
$('#something a').hover(function(){
$(this).addClass("over").removeClass("out");
},
function(){
$(this).removeClass("over").addClass("out");
});
hover changed in 1.4 and funny no one here seems to have bothered checking the jQuery docs...
$("#something a").hover(
function () {
$(this).toggleClass("active")
}
);
Change the colors via css.
Note:
Calling $(selector).hover(handlerInOut) is shorthand for:
$(selector).bind("mouseenter mouseleave",handlerInOut);
:hover is not supported in jQuery (see docs).
It doesn't really make sense either: jQuery selectors are used to select elements. What would ":hover" select?
I'm surprised it even works in 1.3
I don't think it does work in 1.3. As Philippe mentioned, it doesn't make sense.
:hover is an event, not an attribute. So I don't see how that selector could work.
You could either use the hover function as antpaw mentioned - http://docs.jquery.com/Events/hover#overout
or you could set a css style rule. e.g.
$('head').append("<style type='text/css'>#something:hover{foo: bar}</style>");
you can use .hover() function or even better plain css
To me, that selector doesn't make much sense, because it depends on an event by the user. Selectors are more about static content, where as the function hover() can track an event. The user would have to have his mouse on top of the content when you made the call.
There might be some cases that it would be useful, but in the case you mentioned, Jonathon Sampson has the right answer. Use $("#something a").hover(function() {$(this).css("something","thomesing");}); instead.
How jQuery works is that it parses selectors (whether css or regular ones) and then returns the jQuery object. As of today , jQuery doesn't support ':hover' selector.
It might work in Chrome or FF or Safari, but will definitely fail in IE6, 7 and 8.
Great workaround would be to either use jQuery's hover() method.
In more complex cases you want to register mouseenter and mouseleave event handlers on container that you want to select with ':hover', and add/remove '.hover' class.
Once the regular 'hover' class is there, you can easily access that container element from anywhere in the code using '#container.hover' selector.
Let me know if you need help coding this...

Categories