I've got the follow code
<ul>
<li>Google</li>
<li>Facebook</li>
</ul>
<!- hidden divs ->
<div id="1" style="display:none;">Email</div>
<div id="2" style="display:none;"">Social Network</div>
I tried the following code but when I click on a link i would like it to show a div based on the id of the link but it is not working
<script type="text/javascript">
$(document).ready(function()
{
$(".chooserClass").click(function() {
var show = $(this).attr('id');
$(show).show();
});
});
</script>
Change
var show = $(this).attr('id');
$(show).show();
to
var show = $(this).attr('id');
$('#'+ show).show();
You have 2 elements on your page that have th same id, and they are numeric which from experience can cause all kinds of undesired behavior.
The way you want to this is like so:
<ul>
<li>Google</li>
<li>Facebook</li>
</ul>
<!- hidden divs ->
<div id="element1" style="display:none;">Email</div>
<div id="element2" style="display:none;">Social Network</div>
We use a data-show element to store the value of the id of the element that we want to display, in the javascript we can now do this:
<script type="text/javascript">
$(document).ready(function()
{
$(".chooserClass").click(function() {
var show = $(this).data('show');
$('#' + show).show();
});
});
</script>
also note that I am added in the # (for id) in front of the variable when calling the show()
Fiddle demo: http://jsfiddle.net/5U8sW/
Well, here's a quick an dirty answer:
The problem is that you can't have duplicate id's on DOM elements. They should be unique. You can use a data- property to do what you are wanting.
http://jsfiddle.net/725XT/
<ul>
<li>Google</li>
<li>Facebook</li>
</ul>
<!- hidden divs ->
<div id="1" style="display:none;">Email</div>
<div id="2" style="display:none;">Social Network</div>
And your Javascript:
$(document).ready(function()
{
$(".chooserClass").click(function() {
var show = $(this).data('div-id');
console.log(show);
$('#' + show).show();
});
});
When using javascript or jQuery to search for elements with the same IDs, only the first element is picked. I suggest you rename the IDs of the elements to be shown. Take the code below for example.
HTML
<ul>
<li>Google</li>
<li>Facebook</li>
</ul>
<!- hidden divs ->
<div id="d_1" style="display:none;">Email</div>
<div id="d_2" style="display:none;"">Social Network</div>
jQuery
<script type="text/javascript">
$(document).ready(function()
{
$(".chooserClass").click(function() {
var id = $(this).attr('id');
$('#d_'+id).show();
});
});
</script>
jsFiddle
First of all, your IDs should be unique. Thus, the <div> and the <a> must not share the similar ID names. Additionally, AFAIK, in HTML4.1 IDs starting with digits are prohibited(?)
Try the sample I coded above. Since you are using anchors, referencing the 'href' attribute would be more semantically correct.
Cheers!
Related
In my project, there are so many jQuery toggles needed for changing text and icons. Now I’m doing that using:
$("#id1").click(function () {
//Code to toggle display and change icon and text
});
$("#id2").click(function () {
//Same Code to toggle display and change icon and text as above except change in id
});
The problem is that I got so many to toggle, the code is quite long but all I change for each one is the id. So I was wondering if there is any way to make this simple.
Below is a sample pic. I got so many more in single page.
There are two issues here.
How to run the same action on multiple elements
How to know which element you've clicked so that you can run a relevant action on it. (most of the existing answers skip this part).
The first is to use a class for each of the elements you want to click, rather than wire up via an id. You can use a selector similar to [id^=id] but it's just cleaner to use a class.
<div id="id1" class="toggler">...
which allows you to:
$(".toggler").click(function() ...
the second is it associate the clickable with the item you want to toggle. There are many ways to do this, my preferred option is to associate them with data- attributes, eg:
<div class="togger" data-toggle="#toggle1">...
which allows you to:
$(".toggler").click(function() {
$($(this).data("toggle")).toggle();
});
The key here is that this is the element being clicked, so you can do anything else with this such as show/hide an icon inside or change colour.
Example:
$(".toggler").click(function() {
$($(this).data("toggle")).toggle();
$(this).toggleClass("toggled");
});
.toggler { cursor: pointer }
.toggled { background-color: green }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="toggler" data-toggle="#t1">T1</div>
<div class="toggler" data-toggle="#t2">T2</div>
<div class="toggler" data-toggle="#t3">T3</div>
<hr/>
<div id="t1" style='display:none;'>T1 content</div>
<div id="t2" style='display:none;'>T2 content</div>
<div id="t3" style='display:none;'>T3 content</div>
Oh,Can you use a class instead of id?
<ul>
<li class="idx">A</li>
<li class="idx">B</li>
<li class="idx">C</li>
</ul>
$(".idx").click(function(e){
//Code to toggle display and change icon and text
let target = e.target;
//You can do all what you want just base on the `target`;
});
You can store the queries in an array, and iterate over them to perform the same JQuery operation on all of them
let ids = ["#id1", "#id2", "#id3", "#randomID"]
ids.forEach((id) => {
console.log($(id).html())
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li id="id1">A</li>
<li id="id2">B</li>
<li id="id3">C</li>
<li id="randomID">D</li>
</ul>
Or (If like your example) and all of the id's are actually id1, id2, id3, ... etc.
let id = "id";
let n = 3; //amount of id's
for (let i = 1; i <= n; i++) {
console.log($("#" + id + i).html())
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li id="id1">A</li>
<li id="id2">B</li>
<li id="id3">C</li>
</ul>
You can try the below code.
var num = $("#myList").find("li").length;
console.log(num)
for(i=0;i<num;i++){
$("#id"+ i).click(function(e){
let target = e.target;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<ul id="myList">
<li id="id1">A</li>
<li id="id2">B</li>
<li id="id3">C</li>
</ul>
I have this code http://jsfiddle.net/cwahL1tz/
My HTML
<ul class="myFilters">
<li data-type="A">A</li>
<li data-type="B">B</li>
<li data-type="C">C</li>
</ul>
<div class="filter">
<ul class="title">
<li>Assurance</li>
<li>Couverture</li>
<li>Banque</li>
<li>Alimentation</li>
</ul>
<div id="Assurance" class="category">
<ul>
<li>Groupama</li>
</ul>
</div>
<div id="Couverture" class="category">
<ul>
<li>Try it !</li>
</ul>
</div>
<div id="Alimentation" class="category">
<ul>
<li>AN example</li>
</ul>
</div>
</div>
Here's my JS script
jQuery(function ($) {
$('.myFilters li').click(function(){
$(".category").hide();
var v = $(this).text()[0]
$('.title li').hide().filter(function(){
return $(this).text().toUpperCase()[0] == v;
$(".category:first").show();
}).show()
})
$("a[data-toggle]").on("click", function(e) {
e.preventDefault(); // prevent navigating
var selector = $(this).data("toggle"); // get corresponding element
$(".category").hide();
$(selector).show();
});
});
It works fine but I trying to arrange some stuff but I'm stuck.
When I load the page all the links and divs appears, I just only want the divs of the first letter appear.
And when I click on C for example, I want the first div to show from the first link.
Thanks for your help !
EDITED:
On load:
$('.myFilters li:first').trigger('click');
And inside its click:
.first().find('a[data-toggle]:first').trigger('click');
jsfiddle DEMO
You can simply do that with first selecting the element with the right selector and then you can trigger the click event manually :
Show the Assurance content on load :
$('a[data-toggle="#Assurance"]').click();
Show first content on click :
$('.myFilters li').click(function(){
$(".category").hide();
var v = $(this).text()[0]
$('.title li').hide().filter(function(){
return $(this).text().toUpperCase()[0] == v;
}).show()
$('a[data-toggle]:visible:first').click();
})
Updated jsFiddle
Without going into any more javascript, you can display the content the way you would like using css selectors:
.category {display:none;}
.category:nth-of-type(1) {
display:block;
}
http://jsfiddle.net/5ageasm4/1/
Is this what you want. Check the Fiddle
I am basically just triggering the first item in the li
$(".title > li:first").find("a[data-toggle]").trigger("click");
and i am doing the same with the category.
EDIT
I updated my Fiddle
NEW EDIT
Created a new Fiddle, this one just removes all the duplicate code.
So basically i created these 2 functions
that.selectFirstElem = function(selector){
selector.find("a[data-toggle]").trigger("click");
};
that.loadFirstDataToggle = function(input){
return $('.title li').hide().filter(function(){
return $(this).text().toUpperCase()[0] == input;
}).show();
};
And those 2 functions you can just call in the places where you need it.
So I've got 2 <ul> containers each with id's. Inside of them are a list of <li> elements.
The first <ul> is <ul id="coaches-list">. The second is <ul id="players-list">.
There are tags within each <li> that have an id called close (which is a link that I'm using as my selector), which will delete each <li> node once clicked. I'm trying to target each <ul> container to see where it is coming from.
My HTML is:
<!-- coaches box -->
<div class="box">
<div class="heading">
<h3 id="coaches-heading">Coaches</h3>
<a id="coaches" class="filter-align-right">clear all</a>
</div>
<ul id="coaches-list" class="list">
<li><span>Hue Jackson<a class="close"></a></span></li>
<li class="red"><span>Steve Mariuchi<a class="close"></a> </span></li>
</ul>
</div>
<!-- players box -->
<div class="box">
<div class="heading">
<h3 id="players-heading">Players</h3>
<a id="players" class="filter-align-right">clear all</a>
</div>
<ul id="players-list" class="list">
<li><span>Steve Young<a class="close"></a></span></li>
<li><span>Gary Plummer<a class="close"></a></span></li>
<li><span>Jerry Rice<a class="close"></a></span></li>
</ul>
</div>
My remove tag function in jQuery is:
function removeSingleTag() {
$(".close").click(function() {
var $currentId = $(".close").closest("ul").attr("id");
alert($currentId);
// find the closest li element and remove it
$(this).closest("li").fadeOut("normal", function() {
$(this).remove();
return;
});
});
}
Whenever I click on each specific tag, it's removing the proper one I clicked on, although when I'm alerting $currentId, if I have:
var $currentId = $(".close").closest("ul").attr("id");
It alerts 'coaches-list' when I'm clicking on a close selector in both <ul id="coaches-list" class="list"></ul> and <ul id="players-list" class="list"></ul>
If I change that to:
var $currentId = $(".close").parents("ul").attr("id");
It has the same behavior as above, but alerts 'players-list', instead.
So when using closest(), it's returning the very first <ul> id, but when using parents(), it's returning the very last <ul> id.
Anyone know what is going on with this whacky behavior?
It's expected behavior.
You should use:
var $currentId = $(this).closest("ul").attr("id");
$(this) points at the clicked .close.
$(".close") points at the first one found.
It's because you run that selector from click handler you should use this instead:
var $currentId = $(this).closest("ul").attr("id");
Try using this function to get the parent:
var $currentId = $(this).parents().first();
I've never used the .closest() function but according to jQuery what you have specified should work. Either way, try that out and tell me how it goes.
You also need to make it so that it selects the current element by using $(this)
There are several advanced jQuery plugins which filter <div>s by corresponding id or class. This is indeed based on a simple jQuery idea, but I am not sure how to implement it. Consider a menu to show/hide the content as
<ul id="filters" class="menu" indicator="filter">
<li>All</li>
<li>First</li>
<li>Third</li>
</ul>
and we want to control the display of contents:
<div class="box first">Something</div>
<div class="box first third">Something</div>
<div class="box third">Something</div>
What is the simplest jQuery Javascript code to do so?
By default, all <div>s are shown, when we click on a <li> from menu (e.g. FIRST), jQuery will filter the <div>s to only show <div>s in which the class is "first".
Don't use attribute "indicator" as it doesn't exist. Use the class element as below. Also the A elements are not needed.
<ul id="filters" class="menu">
<li class="selected all">All</li>
<li class="first">First</li>
<li class="third">Third</li>
</ul>
Then your script
// hide all divs
$('div.box').css('display','hidden');
// add click handler on control list
$('ul#filters li').click(function() {
var classList =$(this).attr('class').split(/\s+/);
$.each( classList, function(index, item){
if (item != 'selected') {
$('div.'+item).css('display','block');
}
});
});
$(function(){
$('#filters li a').live('click', function(){
$('.box').hide();
indirector = $(this).attr('indicator');
indirector = indirector.substring(1);
if(indirector == '')
$('.box').show();
else
$('div.' + indirector).show();
});
});
Reference
Use the class attribute instead of indicator and try the following:
$('#filters li').click(function(){
$('div.' + $(this).attr('class')).show();
});
for this to work you would have to assign an all class to your first LI as well as all of your DIVs. Hope this helps!
try this code,
$('#filters li').click(function(){
$("div.box").hide();
$('div.box' + $(this).children('a').attr('indicator')).show();
});
greetings,
I have a bunch of <li> items inside a div, the div is scrollable
I would like to have a text box to mark the first li containing a certain text from a textbox and search button.
and the li should became visible :(
I have no clue how to do this :(
Live Demo Updated with scrolling
Markup
<div id='test'>
<ul>
<li>Text</li>
<li>Something</li>
<li>Hey</li>
<li>der</li>
<li>herp</li>
<li>derp</li>
<li>Testing</li>
</ul>
</div>
JS
$('#searchBtn').click(function(){
var searchString = $('#searchText').val(),
foundLi = $('li:contains("' + searchString + '")');
foundLi.addClass('found');
$('#test').animate({ scrollTop: foundLi.offset().top});
});
I'd use the scrollTo plugin: http://flesler.blogspot.com/2007/10/jqueryscrollto.html
then do something like this (not tested)
$('#thediv').scrollTo( $('li:contains("'+yourtext+'")') );
The HTML:
<div style="height: 40px; overflow-y: scroll" id="my_div">
<li>the first li</li>
<li>the second li</li>
<li>the third li</li>
<li>the fourth li</li>
...
</div>
<input type="text" id="my_text_box" />
<input type="submit" id="my_search_button" />
The javascript:
$('#my_search_button').click(function(e) {
var my_search = $('#my_text_box').val(); // the text to search for
var $my_div = $('#my_div'); // the div
$my_div.find('li').each(function(idx, elem) {
$elem = $(elem);
if ($elem.text().indexOf(my_search) != -1) { // if it contains your searched text
$elem.show(); // display it ? only if needed, unclear from question
$elem.addClass('highlighted'); // add your class for the highlight
$my_div.scrollTop($elem.position().top); // scroll to it
return false; // stop the loop
}
});
e.preventDefault(); // stop an actual form from being submitted
});
I am looking for something similar:
Visitors to my site should be able to search within a clickable list of locations (for local weather report).
Ideally, there should be a match mechanism:
as the visitor begins entering the name of the location, that name should be suggested automatically in the search field.
Is there any code like that?
Check this out https://github.com/svapreddy/cssListJS.
Search functionality implemented using pure CSS and little bit JS