unable to hide the ul if it has no li inside it - javascript

I am trying to hide the ul, on page and also using ajax because some parts of the website are ajax based.
<ul class="sub-nav-20-m" id="filtersList_m">
</ul>
so here is the code i am trying but it is not doing anything
window.onload = function(){
alert("hi");
$(".sub-nav-20-m").each(function(){
if($(this).children().length == 0){
$(this).hide();
} else{
$(this).show();
}
}
}

You can use CSS for this:
.sub-nav-20-m:empty {
display: none;
}
See here

It might be useful to first check for empty LI tags for whatever reason and remove them, then if the element is empty, hide it. As a separate function, you could call it after window.onload or after an ajax transaction.
window.onload = function() {
setTimeout(function() {
hideEmptyULs()
}, 2000)
}
function hideEmptyULs() {
$('ul').each(function() {
$(this).children().each(function() {
if ($(this).children().length === 0) $(this).remove()
})
if ($(this).children().length === 0) $(this).hide()
});
}
ul {
border: 1px solid #ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class='thing'></ul>
<ul class='thing2'>
<li></li>
</ul>

Related

How to toggle an animation in Jquery

I am trying to make an animation on a navigation menu where when an option is clicked the other two fade out, since .fadeToggle had problems with positioning for me I decided to just animate the opacity to 0, and then back to 1 when clicked on again. (I left the CSS out the the code posted down below)
https://jsfiddle.net/L703yvke/
<div id='bckDrp'>
<div id='nav'>
<ul id='navLst'>
<li class='navOp' id='hme'>Home</li>
<li class='navOp' id='abt'>About</li>
<li class='navOp' id='prt'>Portfolio</li>
</ul>
</div>
</div>
var main = function(){
$('#hme').click(function(){
$('#abt, #prt').animate({opacity: 0},300 );
});
if($('#abt, #prt').css('opacity') == 0) {
$('#hme').click(function(){
$('#abt, #prt').animate({opacity: 1},300 );
}
)};
}
$(document).ready(main);
The main function only runs once. So you are only doing that if-statement once. Also you are binding click events, which I don't think is what you are expecting it to do. Instead you can simply use a if-else and have your condition inside the click event:
var main = function(){
$('#hme').click(function(){
if($('#abt, #prt').css('opacity') == 0)
$('#abt, #prt').animate({opacity: 1},300 );
else
$('#abt, #prt').animate({opacity: 0},300 );
});
}
Demo
I would heavily recommend handling the animation as a transition in CSS and simply toggling a class.
CSS
#abt, #prt{
opacity:1;
transition: opacity 300s;
}
#abt.hide, #prt.hide{
opacity:0;
}
jQuery
$('#hme').on('click', function(){
$('#abt, #prt').toggleClass('hide');
});
Change your code :
var main = function() {
$('#hme').click(function(){
var op = $('#abt, #prt').css('opacity');
if (op == 1)
$('#abt, #prt').animate({opacity: 0},{duration:300} );
else if(op == 0)
$('#abt, #prt').animate({opacity: 1},{duration:300} );
})
}
$(document).ready(function(){
main();
})
Final code :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id='bckDrp'>
<div id='nav'>
<ul id='navLst'>
<li class='navOp' id='hme'>Home</li>
<li class='navOp' id='abt'>About</li>
<li class='navOp' id='prt'>Portfolio</li>
</ul>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var main = function() {
$('#hme').click(function(){
var op = $('#abt, #prt').css('opacity');
if (op == 1)
$('#abt, #prt').animate({opacity: 0},{duration:300} );
else if(op == 0)
$('#abt, #prt').animate({opacity: 1},{duration:300} );
})
}
$(document).ready(function(){
main();
})
</script>
</body>
</html>
First, you had a typo.... )}; the brackets are reversed. They should be });
Then you could simplify a great deal by just using the built in toggleClass(); function and dynamically getting the clicked element rather than needed to refer to each and every id used. This means you can add/subtract from the #nav list and the function will work regardless of the element ids. The "fade" is all handled in the CSS and you don't need to edit the function at all.
the only thing you'd need to edit from here are nav items in the HTML. (if they change...)
var main = function(){
$('#nav li').on('click', function() {
var thisNav = $(this);
thisNav.toggleClass('active');
$('#nav li').not(thisNav).toggleClass('fadeit');
});
}
$(document).ready(main);
ul { list-style: none; margin: 10px; padding:0; }
li {
display: block;
padding: 5px 10px;
margin: 10px 0;
text-align: center;
text-transform: uppercase;
background: #eee;
border: 1px solid #ddd;
/* below handles the opacity fade */
opacity: 1;
transition: all 1s; }
.active, li:hover { background: #fee; }
/* below handles the opacity fade */
.fadeit { opacity: 0; transition: all 1s; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='bckDrp'>
<div id='nav'>
<ul id='navLst'>
<li class='navOp' id='hme'>Home</li>
<li class='navOp' id='abt'>About</li>
<li class='navOp' id='prt'>Portfolio</li>
</ul>
</div>
</div>
You need set your code with the sentence if, inside the callback .click;
This is necessary because the JS code is loaded only once and in this moment your sentence (if) is read only with the event .loaded()
This is a solution for you:
var main = function(){
$('#hme').click(function(){
$('#abt, #prt').animate({opacity: 0},300 );
if($('#abt, #prt').css('opacity') == 0) {
$('#abt, #prt').animate({opacity: 1},300 );
}else{
$('#abt, #prt').animate({opacity: 0},300 );
};
});
}
$(document).ready(main);

How to activate menu tab after refreshing

How can I activate a menu tab after refreshing?
Here are my code
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<style>
.menu{width: 600px; height: 25; font-size: 18px;}
.menu li{list-style: none; float: left; margin-right: 4px; padding: 5px;}
.menu li:hover, .menu li.active {
background-color: #f90;
}
</style>
</head>
<body>
<ul class="menu">
<li><a href='#'>One</a></li>
<li><a href='#'>Two</a></li>
<li><a href='#'>Three</a></li>
<li><a href='#'>Four</a></li>
</ul>
<script type="text/javascript">
var make_button_active = function()
{
//Get item siblings
var siblings =($(this).siblings());
//Remove active class on all buttons
siblings.each(function (index)
{
$(this).removeClass('active');
}
)
//Add the clicked button class
$(this).addClass('active');
}
//Attach events to menu
$(document).ready(
function()
{
$(".menu li").click(make_button_active);
}
)
</script>
Can anyone tell me How to resolve this issue ?
Just like #Johan said, store your last active tab in a localStorage or cookie. Since there is no noticeable difference in performance between the two. I suggest you use localStorage because it's much easier to use. Like this:
function make_button_active(tab) {
//Get item siblings
var siblings = tab.siblings();
//Remove active class on all buttons
siblings.each(function(){
$(this).removeClass('active');
})
//Add the clicked button class
tab.addClass('active');
}
//Attach events to menu
$(document).ready(function(){
if(localStorage){
var ind = localStorage['tab']
make_button_active($('.menu li').eq(ind));
}
$(".menu li").click(function () {
if(localStorage){
localStorage['tab'] = $(this).index();
}
make_button_active($(this));
});
});
Check out this fiddle.

javascript block the click

I have this code to slide some messages,
JavaScript
$(function() {
$('#bottom_menu li a').click(function(e) {
e.preventDefault();
animateSlider(this.hash);
});
function animateSlider(hash) {
if (!$('#container div.open').length) {
if (hash == '#about') {
openPopup(hash);
}
if (hash == '#contact') {
openPopup(hash);
}
} else {
if (hash == '#about') {
openAndClose(hash)
}
if (hash == '#contact') {
openAndClose(hash)
}
}
}
function openPopup(hash) {
$(hash + '_popup').slideToggle().addClass('open');
}
function openAndClose(hash) {
if ($(hash + '_popup').hasClass('open')) {
$($(hash + '_popup')).slideToggle().removeClass();
} else {
$('#container div.open').slideToggle().removeClass();
$(hash + '_popup').slideToggle().addClass('open');
}
}
});
HTML
<nav id="men55">
<ul id="bottom_menu">
<li style="text-align:left;">
<font face="din" size="4">onde <br />estamos</font>
</li>
<li style="text-align:left;">
<font face="din" size="4">osnossos<br />parceiros</font>
</li>
<li style="text-align:left;">
news <br />press</font>
</li>
</ul>
</nav>
The problem is, when href=#contact or href=#about works fine, but if i want put a href=index2.php?web=teste don´t work... nothing happens... the problem is the javascript block the click inside nav or li
Simply change your initial selector to only select anchor tags whose href property starts with "#" using [href^="#"]. Change:
$('#bottom_menu li a').click(function(e) { ... });
To:
$('#bottom_menu li a[href^="#"]').click(function(e) { ... });
This will ignore any links whose href property doesn't start with "#":
#about /* Prevented */
#contact /* Prevented */
index2.php /* Ignored */
index2.php?web=teste /* Ignored */
index2.php#test /* Ignored */

Change div text with jQuery Toggle

When using slideToggle, how to change the Text close/show?
I did a simple one, but cannot get the text change back.
Here is what I did:
$(document).ready(function(){
$('.open').click(function(){
$('.showpanel').slideToggle('slow');
$(this).text('close');
});
$('.open2').click(function(){
$('.showpanel2').slideToggle('slow');
$(this).text('close');
});
});
body{
font-size:20px;
}
#box{
border:2px solid #000;
width:500px;
min-height:300px;
}
.open,.open2 {
width:450px;
height:50px;
background:blue;
margin:5px auto 0 auto;
color:#fff;
}
.showpanel,.showpanel2{
width:450px;
height:300px;
margin:0 auto 10px auto;
background:red;
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
<div class="open">Show</div>
<div class="showpanel">This is content</div>
<div class="open2">Show</div>
<div class="showpanel2">This is content</div>
</div>
http://jsfiddle.net/9EFNK/
You can use the is() assertion method to check whether the panel is open or closed in the animation's callback and set the text accordingly - http://jsfiddle.net/9EFNK/7/
$('.open').click(function(){
var link = $(this);
$('.showpanel').slideToggle('slow', function() {
if ($(this).is(':visible')) {
link.text('close');
} else {
link.text('open');
}
});
});
Just add a simple if statement to test the text like so
$('.open').click(function(){
$('.showpanel').slideToggle('slow');
if($(this).text() == 'close'){
$(this).text('Show');
} else {
$(this).text('close');
}
});
Like this DEMO
Not the prettiest of methods, but it does the job in a single statement.
$(this).text(($(this).text() == 'Close') ? 'Show' : 'Close');
Use .toggle()
Here is Working Demo
$('.open').click(function(){
$('.showpanel').slideToggle('slow');
}).toggle(function() {
$(this).text('Hide');
}, function() {
$(this).text('Show');
});
check this may be user question is solve Fiddle
Here's an updated version http://jsfiddle.net/9EFNK/1/
You can simply toggle a class on close/open, perform a check for that class and change the contained text accordingly
if( $(this).hasClass('active') )
$(this).text('open');
else
$(this).text('Show');
$(this).toggleClass('active');
try this demo
$(document).ready(function(){
$('.open').toggle(function(){
$('.showpanel').slideToggle('slow');
$(this).text('close');
}, function(){
$('.showpanel').slideToggle('slow');
$(this).text('Show');
});
$('.open2').toggle(function(){
$('.showpanel2').slideToggle('slow');
$(this).text('close');
}, function(){
$('.showpanel2').slideToggle('slow');
$(this).text('Show');
});
});​
Use this
jQuery.fn.toggleText = function() {
var altText = this.data("alt-text");
if (altText) {
this.data("alt-text", this.html());
this.html(altText);
}
};
Here is how you use it
jQuery.fn.toggleText = function() {
var altText = this.data("alt-text");
if (altText) {
this.data("alt-text", this.html());
this.html(altText);
}
};
$('[data-toggle="offcanvas"]').click(function () {
$(this).toggleText();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button data-toggle="offcanvas" data-alt-text="Close">Open</button>
You can even use html provided it's html encoded properly

How to convert unordered list into nicely styled <select> dropdown using jquery?

How do I convert an unordered list in this format
<ul class="selectdropdown">
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
<li>five</li>
<li>six</li>
<li>seven</li>
</ul>
into a dropdown in this format
<select>
<option value="one.html" target="_blank">one</option>
<option value="two.html" target="_blank">two</option>
<option value="three.html" target="_blank">three</option>
<option value="four.html" target="_blank">four</option>
<option value="five.html" target="_blank">five</option>
<option value="six.html" target="_blank">six</option>
<option value="seven.html" target="_blank">seven</option>
</select>
using jQuery?
Edit: When selecting an entry from the select/dropdown the link should open in a new window or tab automatically. I also want to able to style it like: http://www.dfc-e.com/metiers/multimedia/opensource/jqtransform/
$(function() {
$('ul.selectdropdown').each(function() {
var $select = $('<select />');
$(this).find('a').each(function() {
var $option = $('<option />');
$option.attr('value', $(this).attr('href')).html($(this).html());
$select.append($option);
});
$(this).replaceWith($select);
});
});
EDIT
As with any jQuery code you want to run on page load, you have to wrap it inside $(document).ready(function() { ... }); block, or inside it's shorter version $(function() { ... });. I updated the function to show this.
EDIT
There was a bug in my code also, tried to take href from the li element.
$('ul.selectdropdown').each(function() {
var select = $(document.createElement('select')).insertBefore($(this).hide());
$('>li a', this).each(function() {
var a = $(this).click(function() {
if ($(this).attr('target')==='_blank') {
window.open(this.href);
}
else {
window.location.href = this.href;
}
}),
option = $(document.createElement('option')).appendTo(select).val(this.href).html($(this).html()).click(function() {
a.click();
});
});
});
In reply to your last comment, I modified it a little bit but haven't tested it. Let me know.
$('ul.selectdropdown').each(function() {
var list = $(this), select = $(document.createElement('select')).insertBefore($(this).hide());
$('>li a', this).each(function() {
var target = $(this).attr('target'),
option = $(document.createElement('option'))
.appendTo(select)
.val(this.href)
.html($(this).html())
.click(function(){
if(target==='_blank') {
window.open($(this).val());
}
else {
window.location.href = $(this).val();
}
});
});
list.remove();
});
This solution is working also in IE and working with selected item (in anchor tag).
$('ul.selectdropdown').each(function(){
var list=$(this),
select=$(document.createElement('select')).insertBefore($(this).hide()).change(function(){
window.location.href=$(this).val();
});
$('>li a', this).each(function(){
var option=$(document.createElement('option'))
.appendTo(select)
.val(this.href)
.html($(this).html());
if($(this).attr('class') === 'selected'){
option.attr('selected','selected');
}
});
list.remove();
});
Thank you all for posting the codes. My scenario is similar but my situation is for Responsiveness that for x-size it would switch to a dropdown list, then if not x-size, using csswatch to check for the "display" properties of an element that has certain amount of width set to it (eg: 740px). Thought I share this solution for anyone who is interested. This is what I have combined with Tatu' codes. Instead of replacing the html, I created then hide the new html then only add them when necessary:
var $list = $('ul.list');
(listFunc = function(display){
//Less than x-size turns it into a dropdown list
if(display == 'block'){
$list.hide();
if($('.sels').length){
$('.sels').show();
} else {
var $select = $('<select class="sels" />');
$list.find('a').each(function() {
var $option = $('<option />');
$option.attr('value', $(this).attr('href')).html($(this).html());
$select.append($option);
});
$select.insertAfter($list);
$('.sels').on('change', function(){
window.location = this.value;
});
}
} else {
$('.sels').hide();
$list.show();
}
})(element.css('display'));
element.csswatch({
props: 'display'
}).on('css-change', function (event, change) {
return listFunc(change.display);
});
I have recently created a solution where the ul transformed, mimics nearly completely the select.
It has in adition a search for the options of the select and supports the active state. Just add a class with name active and that option will be selected.
It handles the keyboard navigation.
Take a look at the code here: GitHub Code
And a live example here: Code Example
The unordered list must be in the form:
<ul id="...">
<li>...</li>
<li>...</li>
<li><a class="active" href="...">...</a></li>
...
</ul>
To convert the ul to select just call:
$(window).on("load resize", function() {
ulToSelect($("ul#id"), 767);
});
Where #id is an id for the unordered list and 767 is the minimum width of the window for the convertion to take place. This is very useful if you want the convertion to take place only for mobile or tablet.
I found this gorgeous CodePen from #nuckecy for anyone interested:
https://codepen.io/nuckecy/pen/ErPqQm
$(".select").click(function() {
var is_open = $(this).hasClass("open");
if (is_open) {
$(this).removeClass("open");
} else {
$(this).addClass("open");
}
});
$(".select li").click(function() {
var selected_value = $(this).html();
var first_li = $(".select li:first-child").html();
$(".select li:first-child").html(selected_value);
$(this).html(first_li);
});
$(document).mouseup(function(event) {
var target = event.target;
var select = $(".select");
if (!select.is(target) && select.has(target).length === 0) {
select.removeClass("open");
}
});
His default CSS rules:
.select li {
display: none;
cursor: pointer;
padding: 5px 10px;
border-top: 1px solid black;
min-width: 150px;
}
.select li:first-child {
display: block;
border-top: 0px;
}
.select {
border: 1px solid black;
display: inline-block;
padding: 0;
border-radius: 4px;
position: relative;
}
.select li:hover {
background-color: #ddd;
}
.select li:first-child:hover {
background-color: transparent;
}
.select.open li {
display: block;
}
.select span:before {
position: absolute;
top: 5px;
right: 15px;
content: "\2193";
}
.select.open span:before {
content: "\2191";
}

Categories