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');
// ^^^^^^^^^^^^^^
});
Related
so my code which should add a class to an element if the body has a certain class doesnt work. It looks like this:
if ($("body").hasClass("shifter-open")) {
$(".scrollheader").addClass("hovered");
}
I think its because a Jquery code adds this class (shifter-open) to the body with this code:
$( document ).ready(function() {
$("body").addClass("shifter shifter-active");
$('.shifter-handle').click( function() {
$("body").toggleClass("shifter-open", 1000);
});
});
Is there a way to make my code work? and maybe combine these 2 codes into one?
Your conditional :
if ($("body").hasClass("shifter-open")) {
$(".scrollheader").addClass("hovered");
}
Is only going to be evaluated once unless you have a timeout or interval polling it. A better solution might be to combine those two sections into one. Such as:
$( document ).ready(function() {
$("body").addClass("shifter shifter-active");
$('.shifter-handle').click( function() {
$("body").toggleClass("shifter-open", 1000);
$(".scrollheader").toggleClass("hovered");
});
});
Or something like that. You might also want to check the documentation for toggleClass because it doesn't appear to take an integer as a second parameter
Assuming you want to remove the class as well, just imitate exactly what the body is doing. You can toggle the class hovered on your .scrollheader just as the body is toggling its shift-open class.
$( document ).ready(function() {
$("body").addClass("shifter shifter-active");
$('.shifter-handle').click( function() { //When shifter-handle is clicked
$("body").toggleClass("shifter-open"); //Toggle "shifter-open" on the body
$(".scrollheader").toggleClass("hovered"); //Toggle "hovered" on .scrollheader
});
});
Additionally, the second parameter of toggleClass() takes a boolean that determines if the toggle should activate. Your second parameter of 1000 is permanently truthy, so there is no reason at all to include it.
I have to div like this:
<div class="vignettes" id="vignette1"></div>
<div class="vignettes" id="vignette2"></div>
I want to do the same thing on Hover event for both div, let's say change the background to black:
$('.vignettes').hover(function ()
{
//$('.vignettes').css("background", "#000");
$(this.id).css("background", "#000");
},
function()
{
});
The commented line works, but obviously change both div to black when I hover one of them. I want to change only the hovered one. Instead of cloning my hover function with good ids, I want to get the id of the hovered one and change its background dynamically.
The code alert(this.id) pops up the good id, so this.id works.
But $(this.id).css("background", "#000#"); doesn't do anything.
JSFiddle sample
As this is the target, just use $(this).css("background", "#000");
e.g.
$('.vignettes').hover(function ()
{
$(this).css("background", "#000");
},
function()
{
});
It is a bit silly to use a selector to find the current element by its own id as suggested
In fact, most of the time, you do not even need IDs to do this sort of operation, just use classes to change the styling:
e.g. http://jsfiddle.net/TrueBlueAussie/cLws40vr/8/
$('.vignettes').hover(function () {
$(this).addClass("selected");
console.log("test");
},
function () {
$(this).removeClass("selected");
});
You just need to use $(this)
When you are in a function like this, using $(this) will apply to the current element the event applies to.
$('.vignettes').hover(function ()
{
$(this).css("background", "#000");
},
function()
{
});
Updated JSFiddle - http://jsfiddle.net/cLws40vr/4/
As most of the other answers have suggested using this as the selector is the correct way to accomplish what you are trying to do in this case.
$(this).css("background", "#000");
There is another error in your code that was causing your original code not to work. To select using an id you need to add the hash symbol to the beginning of the selector string.
$('#' + this.id).css("background", "#000");
I just thought I would point that out in case anyone was wondering why the original code didn't work.
$(this).css("background", "#000");
alert($(this).attr('id'));
Fiddle http://jsfiddle.net/cLws40vr/5/
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
Let's say I have 10 images on a page, and I want to hide an image when clicking on it.
Each image has an id like: figure1, figure2, figure3, figure i++.
Of course I could write this
$('#figure1').on('click', function() {
$(this).hide();
});
$('#figure2').on('click', function() {
$(this).hide();
});
$('#figure3').on('click', function() {
$(this).hide();
});
and so on but obviously that's not good.
The other thing I thought was creating a function and triggering it with onclick="theFunction(id)", so then I could hide the right image within the function as it knows the id of the image, but when the page loads, obviously JS doesn't know which ID I'm going to delete. How could I make this dynamic?
Any suggestions?
Err I was using class instead of ID in my function :/
function deletePhoto(photo_id, photoPosition) {
$('#photoFigure' + photoPosition).fadeOut(2000);
}
Called like:
<div class="deletePhoto" onclick="deletePhoto({$value['id']}, {$i})">delete</div>
You can give all of them a common class name say figure and use that as the selector:
$('.figure').on('click', function() {
$(this).hide();
});
Or with what you have you could go with attribute starts-with selector
$('[id^="figure"]').on('click', function() {
$(this).hide();
});
or just combine all of them and make a long and ugly selector:
$('#figure1, #figure2, #figure3').on('click', function(){
$(this).hide();
});
For the second part of your question, you can remove those inline click attribute and add a data-attribute save the photoid as is there and just use it to delete, if you have a consistent html structure then you dont event need that, you can select the photo relative to the deletePhoto button.
<div class="deletePhoto" data-photoid="#photoFigure{$i}">delete</div>
and
$('.deletePhoto').on('click', function(){
$($(this).data('photoid')).fadeOut(2000);
//<-- fade out won't delete the element from DOM instead if you really want to remove then try as mentioned below.
//$($(this).data('photoid')).fadeOut(2000, function(){$(this).remove();});
});
OR Could use multiple Select them like this:
Also plz note you are missing ) in your JQ code.
Link : http://api.jquery.com/multiple-selector/
Sample code
$('#figure1,#figure2,#figure2').on('click', function() {
$(this).hide();
});
$(body).on('click','img',function() {
var fig = $(this).attr('id');
$('#' + fig).fadeOut();
});
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.