Multiple items with same class, how to distinguish them with jQuery? - javascript

I have a dropdown list where there are multiple items with class "dropdown" and "menu". On click event I want javascript to find the certain .dropdown that I clicked. Is it possible to implement "this" somewhere on my code and make it work?
$(".dropdown").click(function(e) {
e.preventDefault();
if ($(".menu").is(":visible")) {
$(".menu").slideUp();
$(this).find("li").children(".list").addClass("plus").removeClass("minus");
} else {
$(".menu").slideDown();
$(this).find("li").children(".list").removeClass("plus").addClass("minus");
}
});
Edited afterwards:
So this is my list (please don't pay attention to the fact that "a" is outside of "li"). So I need to find closest "menu" to "dropdown". Already tried closest, find etc. but nothing I tried did the trick. Any suggestions?
<a class="dropdown" href=""><li>Link 1 <div class="plus"></div></li></a>
<ul class="menu">
....

Within the event handling function, this will be set to the element that was clicked.
If that does not help, you should provide more information in your question.

jQuery uses CSS selectors so just do $(".dropdown > .menu") to select the first .menu following a .dropdown. or $(".dropdown .menu:first-child")
edit:
$(".dropdown").click(function()
{
var theNextMenu = $(this).next(".menu");
}

Related

jQuery onclick show first parent div

I have an issue with a show of a parent div at onclick.
As here:
$('#click').click(function() {
$(this).parent().closest('div').slideToggle("fast");
});
http://jsfiddle.net/bk1hLoyb/
I need to show the .show div at the li click, and i need to hide the first when i click another.
Someone know's a method?
Thanks so much
Id's should be unique on the page.
$('.click').click(function() {
$('.show').hide();
$(this).find('.show').slideToggle("fast");
});
http://jsfiddle.net/bk1hLoyb/11/
First Id's must be unique so change it for:
<li class="click">
Bye
<div class="show">Hey</div>
</li>
and the code change it for:
$('.click').click(function() {
$(this).find('div').slideToggle("fast");
});
LIVE DEMO
Some suggestions:
remove all duplicate IDs
if you must use a selector on the li elements, use a class
.show is a child of the li that's clicked, so there's no need to use .parent() or .closest().
Code:
$('.click').click(function() {
$('.show', this).slideToggle("fast");
});
DEMO
BONUS
$(elm).find('.selector') is equivalent to $('.selector', elm)
Also written as jQuery( selector [, context ] )
When context is not specified, it is assumed to be document
Thus $(elm) is equivalent to $(elm, document)
On your "li"s change the id to a class so you can reference multiple divs.
Then on the script looks like this:
$('.click a').click(function() {
var item = $(this);
$(this).parent().siblings().find('.show').slideUp(400,function(){
item.parent().find('.show').slideDown(400);
});
});
See it working on your fiddle (sorry for updating without forking)

Backbone.js – changes to li element don't display immediately

What I have in my template is just a bunch of divs and a list, consisting of multiple li elements. The use case is simple, the li elements are a dropdown and are displayed only on clicking a button. When the dropdown is visible and someone begins to type, the matching li element should be selected, or there should be a visual indication.
My approach is this, on a keyup event, I look for the typed word (this is quite easy) in the li elements. I find a few elements, which I've confirmed. Now, when I try to do something with these elements, nothing seems to happen WHILE the dropdown is open (right now, I'm trying to .toggle()) these elements. Now, when I click the button again (which showed the dropdown in the first place) (this click hides the dropdown), and then click the same button again to reveal the dropdown, voila! The values have been changed as they should be – the matching elements have been hidden/shown.
This has me stumped. For company policies, I can't upload the code up here, but I'll be very thankful if someone else has had this problem before and can help me out.
EDIT:
Code: function to change the dropdown on keypress, this is being fired correctly:
filterOptionsForKeypress: function (event) {
var typedString = this.$('input.filter-button-text').val(),
searchToken = _.trim(typedString.toLowerCase().replace(/ /g, '_')),
matchingLi = this.$("li[data-field^='" + searchToken + "']", this.$el), // makes no difference with or without the context, this.$el
that = this;
if (matchingLi && matchingLi.length) {
this.$(matchingLi[0]).html('kaka'); // this change shows only if the dropdown is hidden + shown again
console.log('trying to move focus', this.$(matchingLi[0]).attr('data-field'));
}
// this.$el.append('Some text'); -- this works, I see the changes as they happen
}
And the template looks something like this:
<div class="filter-button filter-option {{if !model.include}}button-red{{else}}button-green{{/if}} toggle-dropdown" data-dropdown-class="{{if !model.include}}button-red{{else}}button-green{{/if}}">
<div class="filter-button-text">${model.option}</div>
<div class="filter-drop"></div>
<div class="dropdown filter-dropdown">
<ul>
{{each model.config.options}}
<li data-field="${$value.op}" data-include='${$value.include}'>${$value.name}</li>
{{/each}}
</ul>
</div>
</div>
EDIT #2:
When the dropdown is open, this is how the html looks:
OPEN:
CLOSED:
So basically, apart from adding a few styles to the enclosing div and a class 'open', I don't see any differences.
The problem was that we're using a plugin for dropdown menus. So basically, what we saw on the screen wasn't what we found selecting with this.$(). The solution? Look globally and with a :visible filter voila, problem solved.

Javascript: Referring to this element in if condition

I am making a script to make a submenu visible as a dropdown when the menu button is hovered (or onmouseover). I made the if condition refer to this.id="menutoggle1" and check if it's true or false.
If true, it should fire off a function with the statement
document.getElementById("submenu1").style.display="inherit";
It doesn't work, but I assume this has something to do with my if condition. I don't really understand conditions that well, but I hope someone can explain why this is wrong, and maybe even help me fix it.
This is my code;
function submenu_show()
{
if(this.id="menutoggle1" == true)
{
document.getElementById("submenu1").style.display="inherit";
}
}
I know another way that I can achieve the result I want, but then I need to write two functions to show and two functions to hide, for all the menu options that are supposed to have submenus, and it is just messy and ugh.
EDIT: I figured I couldn't make it work without dropping my idea completely, so I just went with the other alternative. I also realized that wasn't really that messy after all, when written properly (it is supposed to be used for several drop downs after all).
Here's the code I used eventally;
<div id="menubutton1" onmouseover="submenu1_show();" onmouseout="submenu1_hide();"></div>
<div id="submenu1" onmouseover="submenu1_show();" onmouseout="submenu1_hide();"></div>
function submenu1_show()
{document.getElementById("submenu1").style.display="inherit";}
function submenu1_hide()
{document.getElementById("submenu1").style.display="none";}
In the current code, this is merky. Its certainly not the element's ID. You could find the element in the function.
function fnName(){
var el = document.getElementById("...");
if(el.id === "something"){ ... }
}
If you want to get the function to do this for a particular ID, you could just add a param to the fnName function and pass that param do the doc.getElByID function.
why not use jQuery to do this for you? With a little bit of CSS and jQuery edits, you can utilize sliding effects and fading effects among other benefits. Look how easy a drop down is with jQuery:
$('nav ul li a').hover(
function() {
$('nav ul li ul').addClass('over');
},
function() {
$('nav ul li ul').removeClass('over');
}
);
Here is a working demo. I know it doesn't answer your question but I do hope this helps you out a little bit!

Jquery select all children within children

I'm sure this will be a simple question but I still struggle with DOM selectors in Jquery so here is a model of my html code:
<fieldset class="product-options" id="product-options-wrapper">
<ul class="options-list">
<li><a href>Item1.1</a></li>
<li><a href>Item1.2</a></li>
<li><a href>Item1.3</a></li>
</ul>
...other html items here
<ul class="options-list">
<li><a href>Item2.1</a></li>
<li><a href>Item2.2</a></li>
<li><a href>Item2.3</a></li>
</ul>
</fieldset>
Now how do I select all of the 'li a' items in both lists (or X number of lists) with class name .options-list and bind them with a click function.
Currently I have:
$('fieldset#product-options-wrapper ul.options-list > li a').bind('click', function(e) {
//code here
});
And it only gets the first options-list.
Thanks, greatly appreciated!
EDIT: If i click on a Item2.X list item first, then it will grab that options list. But as soon as I click on the Item1.x list items it disregards the second .options-list
If you are going to bind to each li element, you should bind it to the ul element instead (helps greatly with performance when there are a lot of events).
$('.options-list', '#product-options-wrapper').bind('click', function(e)
{
e.preventDefault();//In case you don't want to go to a different page
var clicked = e.target;//The href that was clicked
/* If you only want this to happen if the a tag was clicked, add the following line
if(clicked.tagName == 'A')*/
//Rest here
});
How about $('.options-list a').bind('click', function(e) { });?
You can use delegate in this case to make it even simpler. Try this
$('#product-options-wrapper ul.options-list').delegate('li > a', 'click', function(e) {
//code here
});
Your method seems sound to me. I created a test fiddle using your HTML (and an extra anchor to prove that it won't get the click added) and your JS (with minor modifications).
http://jsfiddle.net/chrisvenus/esZxH/1/
The selector you had did work but since you said you wanted the a to be a direct child of the li (or at least I read it that way) I slightly tweaked it in my version above. ARe you sure its not just your function is not doing quite what you want while executing or can you confirm that your click function isn't being run at all?

Changing Style with click in jQuery

i am trying to make a to do list app. When i click a span with class "check" then i want to apply a style. Then the class of the span will change to "uncheck". When click the uncheck then the previous style will restore. Here is the html and jquery what i have done so far.
Problem: Problem is when i first click the span it works The "uncheck" class get removed and "check" class get added. Then the second part not works. I suspect the second part don't working because the "check" class is not in the dom when document.ready() is runs.
Any help will be greatly appreciated! Thanks!
HTML:
<div class="note-body">
<ol>
<li>M2u category shown. M2u category shown M2u category shown M2u category shown.
<span title="Delete" class="delete"></span>
<span title="Task Done!" class="done"></span>
<span class="handle"></span>
<span class="handle"></span>
</li>
<li>M2u category shown</li>
<li>M2u category shown</li>
</ol>
</div>
jQuery:
$('.note-body ol li span.check').click(function(){
$(this).addClass('uncheck').removeClass('check');
$(this).parent().css({'text-decoration':'line-through', 'color':'#5b382e'});
});
$('.note-body ol li span.uncheck').click(function(){
$(this).addClass('check').removeClass('uncheck');
$(this).parent().css({'text-decoration':'none', 'color':'#5b382e'});
});
RESOLVED:
Had to use the live(); because i am adding dom dynamically. Here is the final code (placed the styles in classes):
$('.note-body ol li span.check').live('click', function(){
$(this).addClass('uncheck').removeClass('check');
$(this).parent().addClass('task-done').removeClass('task-notdone');
});
$('.note-body ol li span.uncheck').live('click', function(){
$(this).addClass('check').removeClass('uncheck');
$(this).parent().addClass('task-notdone').removeClass('task-done');
});
You are correct. Since the 'uncheck' class is dynamically added to the DOM, you need to use the jQuery live API. Try this:
$('.note-body ol li span.uncheck').live('click', function(){
$(this).addClass('check').removeClass('uncheck');
$(this).parent().css({'text-decoration':'none', 'color':'#5b382e'});
});
use jquery live or delegate as they are added runtime
http://api.jquery.com/live/
http://api.jquery.com/delegate/
Do you really need an uncheck class? Are there three states check, uncheck and 'nothing'? Getting rid of the uncheck class you could simplify your code.
I would do:
$('.note-body .some_other_identifier').live('click', function() {
$(this).parent().toggleClass('check');
});
Adding
.some_other_identifier {'text-decoration':'line-through'; 'color':'#5b382e'; }
.check .some_other_identifier { 'text-decoration':'none'; 'color':'#5b382e'; }
to your css.

Categories