Dynamic Add/Remove Class Jquery - javascript

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)).)

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"});
});
});

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());
});

Is there a better way to access the first element selected with a JQuery selector?

Is there a better way to write this so I don't have to use the [0] and so I can access the text by the JQuery Text instead of innerText ? I don't want to use innerText for Cross Browser compatibility .
$('#' + controlBestPractice)[0].innerText
Use first if your selector returns more than one element (we don't really know what is inside controlBestPractice, e.g. it could be #div-id p):
$('#' + controlBestPractice).first().text()
As bhamlin pointed out in comments, it appears that you are using id selector, so there should be only one element, so this should work:
$('#' + controlBestPractice).text()
You could try something like this:
$('#' + controlBestPractice + ':eq(0)').text();
or
$('#' + controlBestPractice).first().text()
You dont need to add the [0] on the end since it is a selector by id. The # denotes you are selecting by id and since id's are unique jQuery will only return a single element.
Why are you guys doing .first()? It's an ID there should only be one.
$('#' + controlBestPractice).text()
will work just fine
DEMO
I suppose you might need .first() in the following situation but that'd just be a bad (confusing) way of selecting:
<div id="foo">
<div class="bar">a</div>
<div class="bar">b</div>
<div class="bar">c</div>
</div>
controlBestPractice = "foo .bar";
$('#' + controlBestPractice).text(); // returns abc
$('#' + controlBestPractice).first().text() // returns a

How to execute partial find on dynamic HTML5 data descriptor?

I have a series of images tagged with HTML5 data descriptor "data-type2=[x]" where x is a number of different elements.
e.g.
<img data-type2="pants" class="element" src="#>
I am trying to pass that data field into a jquery function that finds classes in another div (<div class="outfit-list") that has child divs tagged with classes such as:
<div class="pants-001">
<div class="pants-002">
<div class="shoes-001">
etc.
Here is where I am stumped: how do I write a jquery function that accesses data type2 from the item I click (e.g. data-type2="pants"), finds all other divs under .outfit-list with classes that have, for example, "pants" in their class name "pants-002", and hide them? The function I have below does not work - I suspect that's because it's looking for the full name and not partial.
How do I make it perform a partial search to locate the classes that contain the term from data-type2?
<script type="text/javascript">
$(document).ready(function(){
$('.thumbslist .element').click(function(){
$('.outfit-list').find('.'+$(this).data('type2')).hide();
});
});
</script>
You can use the attribute contains selector, [attribute*="value"].
$('.outfit-list').find('[class*="' + $(this).data('type2') + '"]').hide();
You can use the starts with selector. Something like
$(".thumbslist .element").click(function() {
var type2 = $(this).data("type2");
$(".outfit-list").find("div[class^=" + type2 + "]").hide();
});
This plugin adds support for data selectors: http://plugins.jquery.com/project/dataSelector
First of all, the jQuery .data() method is amazing: http://api.jquery.com/data/
You could do:
$("#img1").data('type', 'pants')
// Or whatever else you need to attach data to. You can do this dynamically too!
t = $("#img1").data('type')
// Recall that data at some point
$("div").each(function() {
pat = new RegExp(t)
if ($(this).attr('class').search(pat) !== -1) {
$(this).hide()
}
});
Or even better in Coffeescript
t = $("#img1").data 'type'
$("div").each ->
if ($(#).attr('class').search new RegExp t) isnt -1 then $(#).hide()
May be with something like in this other question
jQuery selector regular expressions
You could just grab the value of the attribute then use it in an attribute selector: http://jsfiddle.net/n73fC/1/

Use Jquery variable to identify a div class/Id

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...

Categories