Add element after specific list item - javascript

I have a list of tabs set up like this. All tabs have a class tab_<number> and the active tab also has an extra class tab_active
Below these tabs there is a div that shows the dynamic content based on which tab is active
<div class="tab_content">xxx</div>
What I'm trying to do is insert the div tab_content below the active tab.
This works, but only on the second click on the tab, which I don't understand why.
The second script I tried, was looping through the different tabs and trying to insert the div like this, but this only works on the last item, because it just loops through it.
/*
// I tried two solutions, this was my first
jQuery(".tabs li").click(function() {
jQuery(".tab_content").insertAfter(jQuery(".tab_active"));
});
*/
// second
var i;
for (i = 0; i < jQuery('.tabs li').length - 1; i++) {
jQuery(".tab_" + i).click(function() {
jQuery(".tab_content").insertAfter(jQuery(".tab_" + i));
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="tabs">
<li class="tab_0 tab_active">1</li>
<li class="tab_1">2</li>
<li class="tab_2">3</li>
<li class="tab_3">4</li>
<li class="tab_4">5</li>
</ul>
<div class="tab_content">xxx</div>
Can you guys/gals see what I'm doing wrong?
Much appreciated!

this can be done in something like following way.
Note though that if there are more tab_* elements in page then update the selector to be more stricter as needed to prevent selecting unexpected element.
$("[class^=tab_]").click(function(){
$(this).append($(".tab_content"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="tabs">
<li class="tab_0 tab_active">1</li>
<li class="tab_1">2</li>
<li class="tab_2">3</li>
<li class="tab_3">4</li>
<li class="tab_4">5</li>
</ul>
<div class="tab_content">xxx</div>

Related

jQuery firing parent functions before children (slideUp and slideDown)

In short, I have a 2 main links (Private Car and Commercial Vehicle) each with a specific class attached to their anchor tags. The same class names are used on the li tags of a second sublink ul to match them with to two top links. The idea is that each time a main link is clicked, the following happens:
The sublink ul slides up
All the li's inside are hidden
The li's with the corresponding main link class are shown
The sublink ul slides down showing only the correct li's
Unfortunately that is not the order that the functions fire in. What happens is this:
The sublink ul slides up
The sublink ul slides down
All list elements inside are hidden
The relevant list elements slide down
Any idea on how I can get the order to fire as I want it?
Here is the code
$('.insurer ul.toplinks a').click(function(e) {
e.preventDefault();
var sublinkCategory = $(this).attr('class'),
subLinksToShow = $(this).parent().parent().parent().find('li.' + sublinkCategory),
subLinksList = $(this).parent().parent().parent().find('ul.sublinks'),
allLinks = $(subLinksList).find('li');
// First time
if ($(subLinksList).is(":hidden")) {
$(subLinksToShow).slideDown();
$(subLinksList).slideDown();
// List visible but new links invisible
} else if ($(subLinksList).is(":visible") && $(subLinksToShow).is(":hidden")) {
$(subLinksList).slideUp(function() {
$(allLinks).hide(function() {
$(subLinksList).slideDown(function() {
$(subLinksToShow).slideDown();
});
});
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="toplinks">
<li>Private Car</li>
<li>Commercial Vehicle</li>
</ul>
<ul class="sublinks">
<li class="privatecar">Key Facts</li>
<li class="privatecar">Policy Wording</li>
<li class="commercialvehicle">Key Facts</li>
<li class="commercialvehicle">Policy Wording</li>
</ul>
Your code isn't working while we don't have the fully code.
This works, note the comments in the code to see what happens on the line under the comment.
$(function() {
// hide by default
$('.sublinks').hide();
$('.toplinks a').on('click', function(e) {
e.preventDefault();
// get the classname
var cl = $(this).attr('class');
// slide up
$('.sublinks').slideUp("slow", function() {
//on callback (= after slide up is done)
// show all links
$('.sublinks li').show();
// hide the ones not having the right class
$('.sublinks li:not(.'+cl+')').hide();
// slide down again
$('.sublinks').slideDown("slow");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="toplinks">
<li>Private Car</li>
<li>Commercial Vehicle</li>
</ul>
<ul class="sublinks">
<li class="privatecar">private Key Facts</li>
<li class="privatecar">private Policy Wording</li>
<li class="commercialvehicle">commercial Key Facts</li>
<li class="commercialvehicle">commercial Policy Wording</li>
</ul>

Add extra pair of UL using JavaScript/JQuery

I have done coding the first part HTML then JavaScript/JQuery. Now I want to surround the final common list with a UL need to be done using JavaScript/JQuery. So the final common list will be surrounded by two UL instead of one. Eg
Final Outcome
<ul id="CommonLister">
<ul> <!--Need to add this-->
<li class="columnItem">John</li>
<li class="columnItem">Mark</li>
</ul><!--Need to add this-->
</ul>
Current Code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<ul id="listOne">
<li class="columnItem">John</li><!--will be removed and put under CommonLister-->
<li class="columnItem">James</li>
<li class="columnItem">Mary</li><!--will be removed and put under CommonLister-->
</ul>
<ul id="listTwo">
<li class="columnItem">John</li><!--will be removed and put under CommonLister-->
<li class="columnItem">Mark</li>
<li class="columnItem">Mary</li><!--will be removed and put under CommonLister-->
</ul>
<ul id="CommonLister">
<li class="columnItem">John</li>
<li class="columnItem">Mark</li>
</ul>
</div>
$(function() {
$('#run-code').on('click', function(e) {
e.preventDefault();
//What were you doing? nope.
var currentItems = {}; //Blank object
var $mergeColumn = $('#CommonLister'); //Common list reference
$('.columnItem').each(function(i, el) {
var $el = $(el); //Notation I use to differentiate between the regular HTML Element and jQuery element
if (!currentItems.hasOwnProperty($el.html())) {
//Has this name come up before? if not, create it.
currentItems[$el.html()] = []; //Make it equal to a brand spanking new array
}
currentItems[$el.html()].push(el);
//Add the item to the array
});
$.each(currentItems, function(name, data) {
//Loop through each name. We don't actually use the name variable because we don't care what someone's name is
if (data.length > 1) {
//Do we have more than 1 element in our array? time to move some stuff
$.each(data, function(i, el) {
var $el = $(el); //See note above
if (i == 0) {
//If this is the first element, let's just go ahead and move it to the merge column ul
$el.appendTo($mergeColumn);
} else {
$el.remove(); //Otherwise, we've already got this element so delete this one.
} //end if/else
}); //end $.each(data)
} //end if data.length >1
}); //end $.each(currentItems)
}); //end $.on()
}); //end $(
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="run-code" class="btn btn-success">Click Me</button>
<h4>List 1</h4>
<ul id="listOne">
<li class="columnItem">John</li>
<!--will be removed and put under CommonLister-->
<li class="columnItem">James</li>
<li class="columnItem">Mary</li>
<!--will be removed and put under CommonLister-->
</ul>
<h4>List 2</h4>
<ul id="listTwo">
<li class="columnItem">John</li>
<!--will be removed and put under CommonLister-->
<li class="columnItem">Mark</li>
<li class="columnItem">Mary</li>
<!--will be removed and put under CommonLister-->
</ul>
<h4>Common List</h4>
<ul id="CommonLister">
<!--Extra ul will be added here-->
</ul>
It's invalid nesting a ul directly in a ul like this but if you have to, you could use jquery wrapAll:
$( "li" ).wrapAll( "<ul></ul>" );
See fiddle: https://jsfiddle.net/9xLt6d9f/
I agree with charlietfl that it seems strange to do it this way. However, to answer your question, the best way to force this improperly formatted HTML code would be hardcode it into your original file. Try the following code for the end of your file:
<h4>Common List</h4>
<ul id="CommonLister">
<ul id="CommonListerSub">
<!--Extra ul will be added here-->
</ul>
</ul>
Then, simply change one line of your code:
var $mergeColumn = $('#CommonListerSub'); //Common list reference
This will force it to list the list items under the nested ul tags.
I hope this is an acceptable solution. If for some reason it doesn't work, please comment as to what additional limitations you have, and perhaps share the link of the page that is giving you the required template or format specifications.

jquery get the height of the submenu

I have the <ul> tag as below. When clicked on the anchor link it should display a div with the ul list items underneath. On the click function of anchor tag, I need to get the complete height of the div (in fact the height of the ul with li items), the submenu
<ul>
<li>
<a></a>
<div>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</li>
</ul>
The html code is as below:
<ul class="menu level-1 plain" id="header-menu">
#{
var i = 1; //Used for submenu ID
}
#foreach (var menuItem in Model.Header.TopLevelNavigation)
{
if (i < 6)
{
<li #Html.Raw(i > Model.MenuMidPoint ? "class=\"sub-menu-nudge-left\"" : "")>
#if (menuItem.ContentLink.HasChildPages())
{
<a href="#sub-menu-#i" class="menu-link js-ui-header-all-menu-drill-down" aria-haspopup="true">
<span class="icon icon-chevron-left #Model.GetBoxIcon(i)"></span>
<span>#menuItem.Name</span>
</a>
<div id="sub-menu-#i" class="sub-menu" aria-label="submenu" aria-hidden="true">
#Html.DisplayEnumerableIContent("<ul class=\"level-2 plain\">{0}</ul>", "<li>{0}</li>", "menu-link", menuItem.ContentLink.GetChildPages(true, true))
</div>
}
</li>
}
i++;
}
</ul>
I tried the jquery function as below:
I tried as below, but I am unable to get the height of the submenu. It never gets into the foreach loop at all. Could anyone please help
$(".menu-link").click(function () {
var $subnavdev = $(this).parent().sublings('sub-menu').siblings('level-2 plain')
var totalHeight = 0;
$subnavdev.find('li').each(function() {
totalHeight += $(this).outerHeight(true);
});
alert(totalHeight);
});
Some of your class selectors were not specified correctly, plus there was a typographical error (all on Line 2).
Update - It also seems the siblings() methods may not be behaving as you intend them to... - And I got the .level-2 selector wrong still - since you need another . before plain. (See below example)
By using the closest() method you can go up to the nearest parent (for example, <li>), then use find() to pick out all .level-2.plain items nested within that parent.
Remember that your $(this) inside the handler function refers to the handled element, (in this case the .menu-link item being clicked.
$(".menu-link").click(function () {
var $subnavdev = $(this).closest('li').find('.level-2.plain');
// ...
});

JQuery each function toggle class

So i have some code like this
<ul>
<li>Example</li>
<li>Example</li>
<li>Example
>
<div class="Menu" style="display:none;">
Some thing
</div>
</li>
<li>Example
>
<div class="Menu" style="display:none;">
Some thing
</div>
</li>
<li>Example</li>
</ul>
Then i use a JS code like this
$("ul li .SplitCtrl").each(function(index) {
$(this).on("click", function(){
$(".Menu").fadeIn(800).slideDown(800);
});
});
But when i using this, all the ".Menu" element will be fade in :(
Please correct my code...
You need to target the specific .Menu that is the one next to this. ELse it will target all element with .Menu class. You can use jquery next
$("ul li .SplitCtrl").each(function(index) {
$(this).on("click", function(){ //changed here
$(this).next(".Menu").fadeIn(800).slideDown(800);
});
});
Check out this JSFIDDLE
jQuery doesn't know which element to open because there are no id's assigned to the menu items. So it opens everything in the .SplitCtrl class because it doesn't know any better. If you assign some id's to the elements, then it will know what to open and when. Using your code so as to minimize modifications, the following will work for you. Note the addition of id's to both of the .SplitCtrl items and the .Menu items, and using the click function and passing in the id of the item that the click originated from. If you embed further elements, this will still work in the case that it isn't the next element following your class, or if you want it to trigger other items on the page in addition to the menu items.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
</head>
<body>
<ul>
<li>Example</li>
<li>Example</li>
<li>Example
>
<div class="Menu" id="menu1" style="display:none;">
Some thing
</div>
</li>
<li>Example
>
<div class="Menu" id="menu2" style="display:none;">
Some thing
</div>
</li>
<li>Example</li>
</ul>
<div id="surprise1" style="display:none;">Now I'm open too!</div>
</body>
</html>
<script>
$(document).ready(function() {
$("ul li .SplitCtrl").click(function(event){
var item = '#menu' + event.target.id;
var surprise = '#surprise' + event.target.id;
$(item).fadeIn(800).slideDown(800); // open the menu item
$(surprise).fadeIn(800).slideDown(800); // open another element
});
});
</script>
In order to toggle the items, you can add something that first hides everything that's open and then makes the newly selected item visible:
//...same code as above to this point
<div id="surprise1" class="Surprise" style="display:none;">Now I'm open too!</div>
</body>
</html>
<script>
$(document).ready(function() {
$("ul li .SplitCtrl").click(function(event){
var item = '#menu' + event.target.id;
var surprise = '#surprise' + event.target.id;
$(".Menu").fadeOut(100); // Hide all items of class .Menu
$(".Surprise").fadeOut(100); // Hide other items of class .Surprise
$(item).fadeIn(800).slideDown(800); // open the menu item
$(surprise).fadeIn(800).slideDown(800); // open another element
});
});
</script>
So now, all the .Menu items in that class are toggled off before the new one is displayed (even though only one displays at a time). Note the added class for "Surprise" to be able to hide all the external elements as well. There are lots of ways to toggle items so this is just one way you could accomplish it.

Change element css based on contents through Javascript

Suppose I have a vertical menu that is coded like this:
<ul class="sub-menu">
<li id="menu-item-1" class="menu-item">
Page1
</li>
<li id="menu-item-2" class="menu-item">
</li>
<li id="menu-item-3" class="menu-item">
Page3
</li>
</ul>
As you can see, the anchor element to page2 doesn't contain any text. Therefore, I want to hide it from the menu. So I'm looking for a javascript solution that does something like this:
if (content of anchor tag equals " ") then
set anchor's parent list element css to visiblity:hidden;
Note that I can't use document.getElementById on this one because the list id's are automatically generated and may change over time. So how do I get to the content of the anchor tag and set the correct list item's CSS?
Thanks.
var link=document.getElementsByTagName("a");
for(var i=0;i<link.length;i++)
if(link[i].innerHTML.replace(/^\s+|\s+$/g, "")==='')
link[i].parentNode.style.display="hidden";
Working Demo
You could use getElementByTagName('li') and then test that class="menu-item'
See this sample.
If you are using jQuery, you can do something like:
$("li").each(function() {
if ($(this).find("a").text() == "")
{
$(this).css('display','none');
}
});
You could use something like this..
$('.sub-menu a').each(function () {
if (this.innerHTML == " ") {
this.parentNode.style.visibility = 'hidden';
}
})

Categories

Resources