Using onClick to change classes with javascript - javascript

I'm working on a menu which animates each li's padding and color properties on mouseover and mouseout, and I wanted to stop the animations and color changes by changing the link's class. So far, I've assigned the animations to stick with a.inactive, and wanted to change the class to a.active through an onclick event. So far, I've found some helpful resources on this site which I'll paste below.
$("#menu li a").click(function (){
if (!$(this).hasClass("inactive")) {
$("a.inactive").removeClass("inactive");
$(this).addClass("active");
}
});
The code above seems to be the ticket, but being a total noob to javascript, I'm having trouble creating a function out of it that can be executed via onClick. Here's the html:
<ul id="menu">
<li class="landscape-architecture"><a class="inactive" href="#project1" onclick="changeClass();"><span class="menu_year">2006/</span>AQUEOUS PLAN</a></li>
Any help would be greatly appreciated. Thanks!
EDIT - Since the code you all have provided below should work but does not, I've gone ahead and put in the code for the mouseover/mouseout animations to see if for some strange reason there would be a conflict:
$('#menu li').click(function () {
window.location = $(this).find('a').attr('href')
}).mouseover(function (){
$(this).find('a.inactive')
.animate( { paddingLeft: padLeft, paddingRight: padRight}, { queue:false, duration:100 } )
.animate( { backgroundColor: colorOver }, { queue:false, duration:200 });
}).mouseout(function () {
$(this).find('a.inactive')
.animate( { paddingLeft: defpadLeft, paddingRight: defpadRight}, { queue:false, duration:100 } )
.animate( { backgroundColor: colorOut }, { queue:false, duration:200 });
});

The above code works for you? Assuming you have a jQuery library loaded in your file, after changing your second line to:
if ($(this).hasClass("inactive")) {
It seems to work fine! The function you have there will run whenever the specified <a> element is clicked. You don't even need the onclick element in the HTML.
If however you do want to utilize the onclick element and turn your current code into a function that may be able to be used elsewhere, you could do something like:
function change_class() {
if ($(this).hasClass("inactive")) {
$(this).removeClass("inactive").addClass("active");
}
});
And use onclick="change_class()" in your HTML.
Here's a JSFiddle to test with: http://jsfiddle.net/TVms6/

Check out this http://api.jquery.com/toggleClass/
$("#menu li a").click(function (){
$(this).toggleClass('inactive')
});

This is not the recommended way of doing stuff these days. While onclick() will work for you, it doesn't quite fit into the unobtrusive policy that people tend to follow with JavaScript these days. Read the description at Wikipedia.
What you should be doing is something like
$('selector').click(function(){
//the action that you want to perform
});
You can assign an id to your anchor tag to be able to easily target it.
In my opinion its best to learn the correct way while you start learning itself, that way it becomes more of a habit from early on.

Related

JQuery OnClick Issue with adding a class

Basically I am adding a class of "id" when a <div> is clicked. The ID is updated to "active"
http://mpagallery.co.uk/exibitions/future/
If you click on the small image, the builder-gallery-item <div> needs to add a id="active" to the end.
Here is what I have tried in my fiddle, and have exactly the same code in an external file, but it just won't work.
jQuery(function ($) {
$(document).ready(function ($) {
$('.builder-gallery-item').on('click', changeClass);
});
});
function changeClass() {
$('.builder-gallery-item').removeAttr('id', 'active');
$(this).attr('id', 'active');
}
I think you're looking for the addClass and removeClass methods
After reading your comment, I would strong encourage you to use classes rather than IDs, because HTML Id elements should be unique
$(document).ready(function () {
$(".builder-gallery-item").on("click", function () {
$('.builder-gallery-item').removeClass('active');
$(this).addClass('active');
});
});
See this JsFiddle
Edit To clean up the comments, the OP has an updated JsFiddle, where the active class is still not being applied to the divs that contain pictures.
Based on that JsFiddle, you are calling addClass('active') on all of the elements with the builder-gallery-item class rather than just the one that was clicked. You should be using:
jQuery(function ($) {
$(".builder-gallery-image").on("click", function () {
$('.builder-gallery-item').removeClass('active');
$(this).closest('div').addClass('active');
});
});
$(this) was actually referencing the figure object, which is why I used the $(this).closest('div') instead. See the Updated Fiddle

Dollar Hash and variable - $('#

So, to show and hide certain DIV tags within my site I got the following codes
$('#ONE').live('click', function () {
$('.hide').css('display', 'none');
$('#b-ONE').css('display', 'block');
});
$('#TWO').live('click', function () {
$('.hide').css('display', 'none');
$('#b-TWO').css('display', 'block');
});
where a click on the div namend "ONE" opens a certain "b-ONE" div, and so on. It works flawlessly but is a pain when the list gets longer. You see where it says "ONE" and "TWO" in the JS ... is there any way I can turn these "ONE" and "TWO" into variables, so I can have up to 40 divs and don't have to type the above code for every DIV, and have a sleek code where I only have to type that finction once with variables?
I'm looking into something like this but lack the in-depth JS / jQuery knowledge:
$('#VARIABLETEXT').live('click', function () {
$('.hide').css('display', 'none');
$('#b-VARIABLETEXT').css('display', 'block');
});
Where a click on a div named "TWENTYONE" shows the div "b-TWENTYONE"
Any help is highly appreciated!
Just use the id of the clicked element when building the selector for the element you want to change:
$('#ONE, #TWO, #THREE').live('click', function () {
$('.hide').css('display', 'none');
$('#b-' + this.id).css('display', 'block');
// ^^^^^^^^^^^^^^
});
The initial selector ("#ONE, #TWO, #THREE") can probably be better written by giving all of those elements the same class attribute, and then using .the-class.
There may also be a structural approach, but as you haven't quoted your HTML, it's impossible to say.
Side note: The live function is not only deprecated, but actually removed from recent vesrions of jQuery. Here's the up-to-date equivalent:
$(document).on('click', '#ONE, #TWO, #THREE', function () {
$('.hide').css('display', 'none');
$('#b-' + this.id).css('display', 'block');
// ^^^^^^^^^^^^^^
});

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/

Changing a specific Instance without ID

Ok, let's say that I have multiple links on a page and I want links to change background color when you roll over them. I would use this code:
$(function() {
$('a').mouseover(function() {
$('a').css('background-color', 'black');
});
});
$(function() {
$('a').mouseleave(function() {
$('a').css('background-color', 'white');
});
});
the problem with this code is that when you roll over one a, all of the links change color. I could give each a a specific ID and make a specific function for each, but is there a more efficient way to do this?
Edit: Additionally, what could I do to set the original background color back to the way it was. If I turn the background back to white, It might not have been white in the first place. How could I fix this?
In your version you use $('a') to call the .css() function on. The Problem is that $('a') selects ALL the a nodes on the page and not only the one that you moved your mouse over. Within the mouseover callback function the this keyword references the node that was the originator of the event. So when you do $(this) within that function you'll create a jQuery object (called a wrapped set) of that node. Now you can call all jquery functions on it, uncluding the .css() function. So here you go:
$(function() {
$('a').mouseover(function() {
$(this).css('background-color', 'black');
});
});
$(function() {
$('a').mouseleave(function() {
$(this).css('background-color', 'white');
});
});
Just so you know, you're all going about it the long and hard way.
// this is like document.onload = function,
// this only needs to be called once, you can put
// all your jQuery in this one function
$(function() {
// the following is a call to all `a` links to add jQuery's own .hover function
// see -> http://api.jquery.com/hover/
$("a").hover(function(eIn) { // this first function is the action taken when
// user hovers over the link
$(this).css({ 'background-color': '#000', 'color': '#fff' });
}, function(eOut) { // this second function is what happens
// when user hover away from the link
$(this).css({ 'background-color': '', 'color': '' });
});
});
​See WORKING Fiddle
ALSO, YOU DONT NEED JQUERY FOR THIS, USE CSS
In CSS:
a:hover {
background-color: #000;
color: #fff;
}​
See it in CSS ONLY HERE

Click link when clicking LI

Ok, I have this list layout that I use, and I want the list row to highlight when I hover it. Now, that's not a problem really, since I can use javascript to change classes for example, but I want the cursor to change to a pointer when hovering and when clicked, I want to follow the link within.
Example code can be found here:
http://sandman.net/test/hover_links.html
I also want to highlight the LI only when there is an eligible link inside it. Preferably using jQuery... Any ideas?
--
I've edited the code to incorporate the suggestion below, and the problem is that the click() action fires when I click other items inside the LI...
--
Right, so now I've edited the code. I've added a class to the link(s) that SHOULD be followed on click, and then a event.stopPropagation() on the links that does NOT have this class, so they are handeled by the browser accordingly.
Thanks again!
jQuery('li:has(a)')
.css('cursor', 'pointer')
.hover(function(){
jQuery(this).addClass('highlight');
}, function(){
jQuery(this).removeClass('highlight');
})
.click(function(e){
if (e.target === this) {
window.location = jQuery('a', this).attr('href');
}
});
This worked for me
$('#element li').hover(function() {
$(this).animate({
backgroundColor: "#4CC9F2"
}, "normal")
}, function() {
$(this).animate({
backgroundColor: "#34BFEC"
}, "normal")
});
I used jquery.color.js plugin it animates really nice hover effect color change

Categories