Use Jquery variable to identify a div class/Id - javascript

I'm sure the answer to this is simple, I've just been able to figure it out.
I have a simple click function which applies to any links in a list being clicked. When one is clicked, I want it to remove a class on a div, which is related to one of the links attributes. E.g:
// The link
<li>example1</li>
// The div
<div id="example1" class="selected"></div>
This is the kinda thing that I've tried, but it aint right:
$("ul.switcher a").click(function(e){
e.preventDefault();
$("#" + $(this().val).removeClass("selected");
});
Any help would be much appreciated! If anyone could also tell me the JavaScript equivalent of doing this too that would be a nice bonus!

Well you're close:
$("ul.switcher a").click(function(e){
e.preventDefault();
$("#" + this.title).removeClass("selected");
});
For this sort of thing, the HTML5 "data-" attribute convention can be very handy. You'd change the markup as follows:
<li>example1</li>
Then in your code you can use the jQuery ".data()" method:
$("ul.switcher a").click(function(e){
e.preventDefault();
$("#" + $(this).data('targetId')).removeClass("selected");
});
That technique allows you to avoid "overloading" other attributes, as you've done with "title". (That's not necessarily a bad thing to do, of course, but sometimes you might want the "title" to be something meaningful, since it will after all show up when the mouse is positioned over the element.)

Change
$("#" + $(this().val).removeClass("selected");
to
$("#" + this.title).removeClass("selected");
That works because the title property of the raw DOM object reflects the "title" attribute. Details here in the draft HTML5 specification, and here in the more-established DOM2 HTML specification.

Try this,
Call the following javascript function on your link click (used jquery as well),
function removeClass()
{
if ( $('#example1').hasClass('selected') ) //Will check whether the div has the mentioned class.
{
$('#example1').removeClass('selected'); //This will remove the specified class from the div.
}
else
{
$('#example1').addClass('class1'); //This can be used to add a class to the div.
}
}
Hope this helps...

Related

Using jQuery, how do you select another element based on the clicked element?

Difficult to phrase this as a question in one small title.
Basically, I have a div:
<div class="sites" id="site1"></div>
which is clickable by the user, and when that div is clicked, I want another div to appear with a similar ID:
<div id="site1_desc" class="description_holder">
Is there a way that when the former div is clicked, I can have the latter selected for use. I have the same div combo for site2, 3, 4 etc. I was thinking something like:
$(document).ready(function(){
$('.sites).click(function(){
$(this&'_desc').css({visibility: "visible"});
});
});
I understand that the above wont work, but I'm not sure what the best way to do this is. I hope the question is clearer now.
Use:
$(document).ready(function(){
$('.sites').click(function(){
$('#'+$(this).attr('id')+'_desc').css({visibility: "visible"});
});
});
Working Fiddle
Specify the target in a data-attribute on the clicked element:
<div class="sites" id="site1" data-target='site1_desc'></div>
$(document).ready(function(){
$('[data-target]').on('click', function(){
$('[data-target=' + $(this).data('target') + ']').show();
}
});
...then it would apply to any element that has a data-target. This pattern is used in a lot of popular front-end frameworks; for example, Twitter Bootstrap's collapsable menus.
You can use this.id to get the id of clicked item , Also you are missing a quote in the selector and need to put # before id selector.
$(document).ready(function(){
$('.sites').click(function(){
//.......^..................
$('#'+this.id+'_desc').css({visibility: "visible"});
//....^....^..........
});
});
+ can be used for concatenation
You need to use this.id instead of this to get the id. Concatenate this event source object id with the string "_desc". You also need to use # for id selector at the beginning of selector.
$(document).ready(function(){
$('.sites').click(function(){
$("#" + this.id + '_desc').css({visibility: "visible"});
});
});

How do I select multiple classes incremented by 1 and their matching children?

I have multiple containers that I need to animate.
Basically: you click on class: box-n (e.g. box-1) and you slideToggle: box-child-n (e.g. box-child-1).
Instead of a click function for every box-n to toggle box-child-n, I want a simple line of code that matches box-n with its children class.
html:
<div class="box-1">Some clickable container</div>
<div class="box-child-1">This should toggle when box-1 is clicked</div>
<div class="box-2">Some clickable container</div>
<div class="box-child-2">This should toggle when box-2 is clicked</div>
Et cetera...
current jquery:
$('.box-1').click(function() { $('.box-child-1').slideToggle() });
$('.box-2').click(function() { $('.box-child-2').slideToggle() });
Sort of desired jquery (allInt function is made up.):
var $n = allInt();
$('.box-' + n).click(function() {
$('.box-child-' + _n).slidetoggle() // local variable to inter alia .box-1
})
I can't seem to think of any solution, so I am asking for help once again.
I appreciate every suggestion you folks give me!
Here's one way to do it that allows for the elements to have other classes besides the ones that you're using to pair them up:
$('div[class*="box-"]').click(function() {
var c = this.className.match(/\bbox-\d+\b/);
if (c)
$('div.' + c[0].replace(/-/, '-child-')).slideToggle();
});
Demo: http://jsfiddle.net/6xM47/
That is, use the [name*=value] attribute contains selector to find any divs with a class attribute that has "box-" in it somewhere. Then when clicked extract the actual class and check that it matches the "box-n" pattern - this allows for multiple (unrelated) classes on the element. If it does match, find the associated "box-child-n" element and toggle it.
Having said all that, I'd suggest structuring the markup more like this:
<div data-child="box-child-1">Some clickable container</div>
<div class="box-child-1">This should toggle when box-1 is clicked</div>
...because then the JS is simple and direct:
$('div[data-child]').click(function() {
$('div.' + $(this).attr('data-child')).slideToggle();
});
Demo: http://jsfiddle.net/6xM47/1/
To just answer your question, this will do the trick :
$("div[class^='box-']").click(function(){
$(this).parent().find('.' + $(this).attr('class').replace('-','-child-') ).slideToggle();
});
jsfiddle here.
Anyway i dont think you use a good approach (you may wrap child into parent div or use ids).

jQuery Design Pattern for Updating Selectors When the HTML Changes

I'm looking for some advice on a making my jQuery selectors more configurable. For example, given the following HTML generated by PHP:
<ul id="my-list">
<li>first</li>
<li>second</li>
</ul>
And a bit of jQuery:
$(function() {
$(document).on("click", "#my-list li", function() {
alert("You clicked " + $(this).text());
});
});
So far so good, but then one day the designer comes along and renames the id "my-list" to "list-of-numbers", and the javascript stops working. Currently the solution is remembering to grep through the code for any references to "my-list", but that's very faulty. Is there a jQuery design pattern for making the selectors configurable?
This can be called 'selector selection.' You can define a set of variables that have the selectors in them as a solution:
var selectors = { myLi: "#my-list li",
myUl: "#my-div ul" };
Then you can simply do an object lookup to get the selector:
$(selectors.myLi);
This has the advantage of being readable and dynamic; however, in your example scenario where someone changes the ID, this would not be very helpful unless it's explicitly noted somewhere in your code that changes are necessary.
You might want to consider doing some delegation and using custom data attributes to define roles.
Define a set of selectors at the beginning of your JS-Code (don't forget to add a comment for what you use it):
var selectors = {
'listSelector':'#my-list li' /* DESC */,
'nextSelector': '.whatever'
}
and use them in your queries:
$(document).on("click", selectors.listSelector, function() {
alert("You clicked " + $(this).text());
});

Dynamic Add/Remove Class Jquery

I am creating an autosuggest box that has a of suggestion returned to it, and I am trying to add/remove the class "searchsuggestinnerulhighlight" to individual links. Here is the dynamically returned ta
<DIV id="searchsuggestinner">
<UL id=searchsuggestinnerul>
<LI>
appalachian trail
</LI>
</UL>
</DIV>
And here is my jQuery:
$(".hoverme").live("mouseover mouseout", function(event) {
if ( event.type == "mouseover" ) {
$("#" + mocount).removeClass("searchsuggestinnerulhighlight");
mocount = $(this).attr('id');
$("#" + mocount).addClass("searchsuggestinnerulhighlight");
} else {
$("#" + mocount).removeClass("searchsuggestinnerulhighlight");
}
});
Originally I had .css("background-color"... and now I've changed it to add class and remove class and it does not work. Any ideas?
Change:
$("#" + mocount).add("searchsuggestinnerulhighlight");
To:
$("#" + mocount).addClass("searchsuggestinnerulhighlight");
mocount = $(this).attr('id');
$("#" + mocount)
That's seriously dodgy jQuery!
First, you don't need attr to get the id. You can get it with this.id. This is far, far quicker.
Second, you don't need to get the id to get a jQuery selection containing the clicked element. Just use $(this) instead.
Finally, as Gabe has said, use addClass rather than add. So, all in all:
$(this).addClass('searchsuggestinnerulhighlight');
One other thing, though -- using a ID value starting with a number was not allowed in HTML before HTML5. Its behaviour is not guaranteed.
I would put this in a comment, but I can't. Implement lonesomeday's changes, but when he uses $(this).id, try just using this.id as 'this' should already be a jquery object. (We don't want $($(this)).)

How can I use multiple Floating Help Dialogue by using 'class' instead of 'id'?

I need to use multiple floating help dialog boxes in a page. I have tried it by using 'display:block' and 'display:none' and used ID in javascript. I cannot use classes since I have multiple of them on the same page and if I use classes then all of them will be displayed/hide at the same time. However, as the number of help items are increasing in the page, I have to go back to the javascript and add more lines ...
for example:
$(document).ready(function() {
$("#help-icon1").click(function() {
$('#help-details1').css('display', 'block');
});
$("#help-icon2").click(function() {
$('#help-details2').css('display', 'block');
});
$("#help-icon3").click(function() {
$('#help-details3').css('display', 'block');
});
});
Each of them also have close icons and they should be disappeared if clicked on that close icon or clicked anywhere in the page. That means I have to write javascript functions 3 times for all the different close icons.
I tried to rely on jquery's "next" feature, but since there are many layers (div/p/span) in between the areas where the help icon is places and the help text, it becomes problamatic. Any idea or any better way to resolve this?
Thanks in advance.
I'm not quite sure I understand what you are looking for, but you can set up all the click handlers in one step, and have each one refer to itself in the handler:
jQuery(".help-icon").click(function() {
jQuery(this).css('display', 'block');
});
You can add additional class names to an element.
A div can be hidden by default, and a new class can be appended to it - to "overrule" the previous style (Hence the name Cascading Style Sheets)
<div class="hidden exception"></div>
If an element is clicked, you can append a new classname like so:
$('.target').addClass('newclass');
more info:
http://api.jquery.com/addClass/
I've not done it using JQuery but what you need is "unobtrusive javascript".
It does get done by using a class. Say you have images you all want highlighted:
<img src="pic1.png" onMouseover="this.src='hi_pic1.png';" />
so they all have the same behaviour. Give them a class:
<img src="pic1.png" class="hi" />
Then at load time, on in the script at the end of your page, yahoo-style, you write an initialisation to
- grab every element of the class
- add the event(s) you want
- set the event to use the appropriate data, e.g. by using this and by using systematic names like pic1 -> hi_pic1.
Hope this helps,
Charles
Have you tried the jQuery .each function?
EDIT: Like the following
$(".help-icon").each(function(idx, elm){
elm.click(function(){
...
})
});
If all of your help icons have the same class you can use jQuery's each function to loop through them, retrieve the associated id, replace "icon" with "detail" in the id (so #help-icon3 would become #help-detail3), and then use that to update the panel. Something like:
$(".help-icon").each(function() {
var detailsId = $(this).attr("id").replace("icon", "details");
$("#" + detailsId).css('display', 'block');
});
Let's just ASSUME that you need to use IDs for some unknown reason. Here's your answer to combine efforts:
$("#help-icon1").add("#help-icon2").add("#help-icon3").click(function() {
$(this).css('display', 'block');
});
Which equates to:
$("#help-icon1, #help-icon2, #help-icon3").click(function() {
$(this).css('display', 'block');
});
But really, you don't need to use unique IDs like this without some pretty good reasons.

Categories