jquery toggle id's instead of classes? - javascript

is there a way to make a toggle function that first of all toggles only one css style element, such as background-color or something like that. and that selects an id instead of a class, for i know of the toggleClass, but im just wondering if it's possible with ids instead?
$("#gallery").load('http://localhost/index.php/site/gallerys_avalible/ #gallerys_avalible');
$('li').live('click', function(e) {
e.preventDefault();
if(!clickCount >=1) {
$(this).css("background-color","#CC0000");
clickCount++;
}
console.log("I have been clicked!");
return false;
});

You really should use classes for that. IDs are unique within a page and should be used as points where you catch events ( via $.live() or some other method which uses event delegation ). Besides , if you think of using IDs because they have higher specificity in CSS rules , then you are going the wrong way.
In short: bad idea, stick to toggling classes.

EDIT:
After reading OP's comment - I believe this is what he is looking for a way to highlight an "active" link on click. And Yes, teresko is definitely right that you should be toggling the classes, not the ID's.
This is the essence of a jQuery snippet that you may be looking for:
$("li").bind('click', function(){
// remove the active class if it's there
if($("li.active").length) $("li.active").removeClass('active');
// add teh active class to the clicked element
$(this).addClass('active');
});
Demo
Check out the jQuery toggle api.
It's a little confusing because a simple google search on jQuery toggle brings you to the show/hide toggle documentation. But, .toggle() can be used to alternate functions - you can even add more than two.
like so...
$("el").toggle(
function(){
$(this).css('background-color', 'red');
},
function(){
$(this).css('background-color, ''); // sets the bg-color to nothing
});

jQuery doesnt has toggleId() function . But you can create your own id toggle function .
function toggleId(className,id)
{
var tag = document.querySelector('.'+className);
tag.id = tag.getAttribute("id") ? '' : id;
}
toggleId("myClass","id");
this will toggle id ( id and NULL ) of myClass element .
another example for toggling between two id
suppose you want to toggle between two id ( id1 and id2 ) of an element then
function toggleId(className,id1,id2)
{
var tag = document.querySelector('.'+className);
tag.id = tag.getAttribute("id") ? id2 : id1;
}
toggleId("myClass","id1","id2");

$("click-element").bind('click', function(){
if($("your-element").is('#yourIdValue')){
$('your-element').removeAttr('id');
}else{
$('your-element').attr('id', 'yourIdValue');
}
});
});

Related

Multiple clicks on same element removes classes

I got the problem that I wanted to add and remove classes on clicking an element. But if I click the same element twice, the added classes will be removed. I don't really get whats the problem here.
$('#01').click( function() {
$(".d1").removeClass("show-forms");
$(".d2").removeClass("show-forms");
$(".pick-notice").toggleClass("hide-forms");
$(".d0").removeClass( "hide-forms" );
$(".d0").toggleClass("show-forms");
} );
Also is there a way to use the same function for more elements, something like this:
$('#01, #02, #03').click( function() {...
I tried this but it didnt worked
$('#01', '#02', '#03').click( function() {...
To assign the same function to multiple selectors your first code should work (see here for reference: https://api.jquery.com/multiple-selector/)
$('#01, #02, #03').click( function() {} );
It's not overly clear from your example where you are adding the classes, I think you are probably looking to use addClass (https://api.jquery.com/addClass/) as opposed to toggleClass (https://api.jquery.com/toggleClass/). addClass adds the class to the selected element. Whereas toggleClass will add the class to the selected element if it doesn't already have the class, and if it does have the class it will remove it. So that could be why the second time you click it removes the class?
Try the following:
$('#01').click( function() {
$(".d1").removeClass("show-forms");
$(".d2").removeClass("show-forms");
$(".pick-notice").addClass("hide-forms");
$(".d0").removeClass( "hide-forms" );
$(".d0").addClass("show-forms");
} );
Or if you want multiple selectors:
$('#01, #02, #03').click( function() {
$(".d1").removeClass("show-forms");
$(".d2").removeClass("show-forms");
$(".pick-notice").addClass("hide-forms");
$(".d0").removeClass( "hide-forms" );
$(".d0").addClass("show-forms");
} );
You can use this for selecting muntiple class at a time :
$("#01, #02, #03").click( function() {...});
This will work on each Id
I don't get the first part of your question but for the second part of your question:
I think it'd be a much better solution to make it a class
so 01,02,03 are all a certain class (i.e. .clickable)
with this you can just $(.clickable).click(function(){

Jquery Mobile Filter system, can't hide multiple divs

I'm making a Jquery Mobile app and have a page with 15 or so divs with class', I'm trying to make a filtering system so that when you press a button some of these divs disappear depending on the class. There are 3 groups and they all have an "all" class to display everything making 4 classes total.
Unfortunately most of the js I use never works even if I set up a jsfiddle for jquery mobile when I put it into my app it doesn't seem to work.
I wanted to use
function show(target) {
document.getElementsByClassName(target).style.display = 'block';
}
function hide(target) {
document.getElementsByClassName(target).style.display = 'none';
}
But that doesn't work whereas document.getElementById seems to work fine. However obviously I can only hide/show 1 div per button..
I was wondering if there was a work around for this or something completely different I should try?
Here's a jsfiddle of what I have: http://jsfiddle.net/tzcx7gky/
It's completely broken in jsfiddle but it works fine in my code, which is odd..
You don't need seperate hide - show functions. The following would take care of all.
$('a').on("click",function()
{
$("#scroll_content div").hide(); // initially hide all divs inside the element with id = scroll_content
var target = $(this).text().toLowerCase(); // find the class you wish to show using the text of the a tag clicked ( I would prefer using data-attr in this case but I'll leave the choice upto you.
$("." + target).show(); // show the element with the class target.
});
Working example : http://jsfiddle.net/tzcx7gky/2/
getElementsByClassName returns an array of elements. So you would have to itterate over the array and then set the display property on each one. Since you are already using jQuery you can use it to do it for all the elements.
function show(target) {
/* jQuery uses CSS selectors to grab elements
so we have to prefix the target with "."
Alternativley we could pass in the whole selector in the
function so we don't have to prefix it e.g.
show('.all')
$(target).show();
*/
$("."+target).show();
}
function hide(target) {
$("."+target).hide();
}
Here is the same implementation in the vanilla js framework
function show(target) {
var elements = document.getElementsByClassName(target);
elements.forEach(function(element){element.style.display = 'block';});
}
function hide(target) {
var elements = document.getElementsByClassName(target);
elements.forEach(function(element){element.style.display = 'none';});
}
note that getElementById returns a single element since id's are unique and there should only be one element with one id on the page. That is why it was working for you.

Toggle between selected classes

I find my self doing this a lot:
$(document).on("click","li",function(){
$(".selected").removeClass("selected"); // Remove any old selected
$(this).addClass("selected"); // Apply selected to this element
});
Is there a better and less repetitive way of doing a task like this? Like toggle a class. Btw, only one element can be selected at a given time.
Thanks.
A more efficient way is to keep track of the last selected item:
var $selected = null;
$(document).on("click", "li", function() {
if ($selected) {
$selected.removeClass('selected');
}
$selected = $(this).addClass('selected');
});
Of course, this should work as long as that particular function is the only one that will ever add / remove the selected class.
This could optionally be wrapped inside a closure to remove the $selected variable.
Btw, using document as the anchor for your delegation isn't best practice. It's better to choose the nearest node that will not get removed from the document.
Update
As Kevin B has mentioned, you could eliminate the branch like so:
var $selected = $();
$(document).on("click", "li", function() {
$selected.removeClass('selected');
$selected = $(this).addClass('selected');
});
The ability to use $() was introduced in 1.4; before that you would use $([]).
You can do this:
<script>
$(document).ready(function(){
$(this).on("click", "li", function() {
$(this).addClass('selected').siblings().removeClass('selected');
});
});
</script>
After debating with Jack I propose mine.
Assuming your list is here :
var $myList = $('#list');
Then:
$myList.on("click","li",function(){
$(".selected",$myList).removeClass("selected"); // Remove any old selected
$(this).addClass("selected"); // Apply selected to this element
});
or
$myList.on("click","li",function(){
$(this).siblings(".selected").removeClass("selected"); // Remove any old selected
$(this).addClass("selected"); // Apply selected to this element
});
Your way of doing it is good enough for me but Jack's is faster and mine is in between both.
I like this one because you don't need to assume there will only be one selected element. And searching is faster when we provide context as far as I know
Thinking about this, you could keep your list elements in a variable, such as:
var $liElements = $('#yourContainer > li');
$(document).on("click","li",function(){
$liElements.not($(this)).removeClass("selected");
$(this).addClass("selected");
});
The notion of keeping track of the current element is the same as the other answers, but you can wrap this logic up cleanly in a function such as
function class_swapper=function(cls){
var cur;
return function(elt){
if (cur) { cur.classList.remove(cls); }
elt.classList.add(cls);
cur=elt;
};
};
A call to class_swapper returns a function used to actually apply the specified class to a particular element (and remove it from the previous one, which is remembered inside the function). You can use this as follows:
var swapper=class_swapper("selected");
swapper(elt1);
swapper(elt2);
or in terms of your example
$(document).on("click","li",function(){swapper(this);});
I've used classList.add and classList.remove, which is a classy way (ouch) of manipulating classes in modern browsers, but of course these could be replaced by jQuery's addClass etc. as necessary.

Using jquery 1.4 or javascript how would I target a specific link using a variable

HTML:
I've attached a simplified example of the problem I'm facing:
<h2>Product2</h2>
<div id="products">
<a class="my-product1" href="#"><span>my-product1<span></a>
<a class="my-product2" href="#"><span>my-product2<span></a>
<a class="my-product3" href="#"><span>my-product3<span></a>
<a class="my-product4" href="#"><span>my-product4<span></a>
<a class="my-product5" href="#"><span>my-product5<span></a>
</div>​
Javascript:
I'm already pulling myProduct from the page title and forcing lowercase. Next I'm attempting to remove this product from the group of links based on its class. Its quite possible this is jquery101 however I can't figure out how to add a class to a link using a variable to determine which class to select. In this example lets assume var myProduct = Product2
function removeProduct(myProduct){
$("a.myProduct").addClass("display-none");
};
Also, I am still learning so if you have the time a Brief explination of why what i'm doing is wrong would go a long way. Thanks for your time!
Simply concat the class name to the selector string:
$("a."+variable)...
Extra info as you requested:
Don't use a class "display-none"... change it's name or use jQuery native code that hides elements(hide(docs))
function removeProduct(myProduct){
$("a." + myProduct).hide();
};
Changing css rules is with the css(docs) function:
function removeProduct(myProduct){
$("a." + myProduct).css('display', 'none');
};
Adding class is with addClass function:
function removeProduct(myProduct){
$("a." + myProduct).addClass('someClass');
};
Change myProduct and removeProduct names to more meaningful variable names:
function hideAnchorElement(className){
$("a." + className).hide();
}
The class attribute / property is used as a generic selector - ie you can apply a class to multiple objects ... the id attribute / property is used for specific selection - and are unique. I suggest you change your HTML to use ids instead of classs
Try something like :
function removeProduct(myProduct){
$("a."+myProduct).css("display","none");
};
uses .css() to change the display property to none
or
function removeProduct(myProduct){
$("a."+myProduct).hide();
};
.hide() does the same thing as the .css() method does above
or
function removeProduct(myProduct){
$("a."+myProduct).addClass("yourclass");
};
where yourclass is a class you want to apply to an element.
And may I suggest you take a look at How jQuery works
Are you looking for this:
function removeProduct(myProduct){
$("a."+myProduct).addClass("display-none");
};
Separating the string selector from the variable
Try this if you want to hide the link on click event
$(function(){
$('#products a').on('click', function(e){
e.preventDefault();
$(this).hide();
});
});​
A fiddle is here.

Jquery problem onclick add class and remove class

first time posting here. I'm a beginner in jquery and i ran into some grey area. Hopefully i can find my answer here and learn from it also :)
So i have a let's say 10 different div. All has the same class. And everytime I click on the div it has to add another class (in this case background-color in css). For that I have this:
$(document).ready(function() {
$(".menucardmenu").click(function(){
if($(this).hasClass("menucardmenu")) {
$(this).addClass("backgroundmenucard");
}
else {
alert ("condition false");
}
});
});
But the question now is, how can i make that only one div can have that background-color (in my case backgroundmenucard). Depending one which div the user click, that div will have the background-color, and the previous div (that was clicked) should reset it back to normal. I can do it with this right?:
$(this).removeClass("backgroundmenucard");
does anyone know the answer to this???
Regards,
Andrew
try the following:
$(".menucardmenu").click(function(){
$(".backgroundmenucard").removeClass("backgroundmenucard");
$(this).addClass("backgroundmenucard");
});
Demo: http://jsfiddle.net/r2Sua/
(I remove the if because it's useless in this case)
Remove from all...
$(".menucardmenu").removeClass("backgroundmenucard");
Then add to this
$(function() // shorthand for document ready
{
var $divs = $('div.menucardmenu'), // standard jQuery "cache" idiom
BG_CLASS = 'backgroundmenucard'; // stay DRY, less prone to typos
$divs.live('click', function() // use .live to bind only 1 event listener
{
// remove the class from all divs
$divs.removeClass(BG_CLASS);
// add the class to this div
$(this).addClass(BG_CLASS);
}
});
});
The if($(this).hasClass("menucardmenu")) check is completely unnecessary since you're already selecting elements which have that class. It will always evaluate to true.
$('.menucardmenu').click(function(){
$('.menucardmenu').removeClass('backgroundmenucard');
$(this).addClass('backgroundmenucard');
});
Another option would be:
$(".menucardmenu").not(this).removeClass("backgroundmenucard");
$(this).addClass("backgroundmenucard");
This way you don't remove and add the class to the specific (this) element

Categories

Resources