jQuery AddClass and RemoveClass function for multiple element throughout web page - javascript

I submitted my code on a code review site and it highlighted that have duplicate functions within my script which can be seen below.
$(document).ready(function () {
$('#search-btn').click(function () {
$('.search-bar-wrap').toggleClass('searchActive');
$('.more-menu').removeClass('moreMenuActive');
$('account-menu').removeClass('acMenuActive');
});
$('.more-btn').click(function () {
$('.more-menu').toggleClass('moreMenuActive');
$('.account-menu').removeClass('acMenuActive');
$('.nav-bar-wrap').removeClass('searchActive');
});
$('.ac-btn').click(function () {
$('.account-menu').toggleClass('acMenuActive');
$('.nav-bar-wrap').removeClass('searchActive');
$('.more-menu').removeClass('moreMenuActive');
});
// MOBILE
$('#mobile-menu').click(function () {
$('.mobile-menu').toggleClass('mobileMenuActive');
$('.m-accord-dwn').removeClass('accordionActive');
});
$('.active-mobile-menu').click(function () {
$('.mobile-menu').toggleClass('mobileMenuActive');
$('.m-accord-dwn').removeClass('accordionActive');
});
$('.mobile-accordion').click(function () {
$('.m-accord-dwn').toggleClass('accordionActive');
});
});
The click functions demonstrated above are adding and removing classes to show can hidden element on the web page and to also give the click but an active state etc. I am trying to follow best practices for me code. Based on my code above is there a way create a global active function? Jsfiddle

The way to eliminate redundant code is to use classes and structure in your markup. By structuring the markup, the same class should be able to be applied to multiple elements, not just one element like you currently have.
You only need one style in your CSS:
.inactive {
visibility: hidden;
}
Then change your markup so each element to be hidden/shown has a "container" element around it and its button. The buttons that toggle the visibility should all have the "toggle-btn" class. And the elements to be hidden/shown all have the "pane" and "inactive" classes.
<header ...>
<div class="container">
<a class="toggle-btn ...">more</a>
<div class="pane inactive ...">
...
</div>
</div>
<div class="container">
<a class="toggle-btn ...">account</a>
<div class="pane inactive ...">
...
</div>
</div>
<div class="container">
<a class="toggle-btn ...">search</a>
<article class="pane inactive ...">
...
</article>
</div>
</header>
Now your JavaScript can be:
$(document).ready(function() {
$('.toggle-btn').click(function() {
var $pane = $(this).closest('.container').find('.pane');
if ($pane.hasClass('inactive')) {
$('.container .pane').addClass('inactive');
$pane.removeClass('inactive');
} else {
$pane.addClass('inactive');
}
});
});
Notice how you only need one event handler registered. Inside the event handler this references the button that was clicked. The "pane" element is found by first using .closest() to get the container element and then .find().
jsfiddle

Related

How to hide an element in if statement?

I am making an html change to a CMS that will affect all pages when the changes are live. I would like this html alert to only affect 1 specific page. I am attempting to do an if statement for the page title.
The logic is that if the page title is Test Article Two then show the html that I have put in place, if not then display=none. With this logic in place, I am viewing the html on all pages not just the one I want it to show.
<div class="container">
<div class="title-wrapper">
<span id="article-banner-country">#countryFullText</span> /
<span id="article-banner-category">#subCatText</span>
<div id="article-banner-title">#pageTitle</div>
<!--page alert -->
<div class="feedback-container content-desktop" id="alert-dialog">
<div class="feedback-left">
<p>Have any feedback? Reach out to us!</p>
</div>
<div class="feedback-right">
<button class="feedback-button">Give Feedback</button>
<button class="feedback-button">Dismiss</button>
</div>
</div>
</div>
</div>
<script>
function showAlert() {
if(#pageTitle === "Test Article Two") {
document.getElementById('alert-dialog').style.display = 'block';
}else {
document.getElementById('alert-dialog').style.display = 'none';
}
}
</script>
I'd recommend changing a class on the body element so that you can use CSS for the styling.
HTML: nothing really changed here
<body>
<div class="container">
<div class="title-wrapper">
<span id="article-banner-country">#countryFullText</span> /
<span id="article-banner-category">#subCatText</span>
<div id="article-banner-title">#pageTitle</div>
<div class="feedback-container content-desktop" id="alert-dialog">
<div class="feedback-left">
<p>Have any feedback? Reach out to us!</p>
</div>
<div class="feedback-right">
<button class="feedback-button">Give Feedback</button>
<button class="feedback-button">Dismiss</button>
</div>
</div>
</div>
</div>
</div>
</body>
javascript: just check the document.title and add the class the the body element
<script>
if(document.title === "Test Article Two") {
document.body.classList.add("show-alert");
}
</script>
Use CSS for the styling. Always hide #alert-dialog and only show it when we add the class to the body.
<style>
#alert-dialog {
display: none;
}
.show-alert #alert-dialog {
display: block;
}
</style>
If you are making static pages or using server side rendering, you could add logic to add a class to show or hide the alert element without adding more javascript to the page. It will have the relevant class(es) when the html is generated and delivered. This way you won't have to create a function, call it and manipulate the DOM after everything is rendered.
I may have missed this in the code above, are you calling the showAlert function anywhere? If not, your alert won't be shown (or will be shown depending on the default styles).
One thing I'd caution against is the imperative nature of the code here. If you wanted to reuse this alert functionality on another page, you'd have to add another more logic to detect another page title every time you wanted to use the alert. Since you are using a CMS, you might consider adding a flag to show the alert, and on this specific page, turn that flag on.
If you wanted to use the function strategy, I'd set your default alert styles:
#alert-dialog {
display: none;
}
.show {
display: block;
}
and try something like this:
<script>
function showAlert() {
if(document.title === "Test Article Two") {
document.getElementById('alert-dialog').classList.add('show');
}
}
document.addEventListener("DOMContentLoaded", showAlert);
</script>
Another alternative is to take a look at the path of the page this is supposed to be on (window.location.pathname) and using regex to see if it matches what you want. I'd recommend that over looking at the title since it's more likely the title of the page will change rather than the url.
In JavaScript, you can access the page title with document.title. You should change the script like this:
function showAlert() {
if(document.title === "Test Article Two") {
document.getElementById('alert-dialog').style.display = 'block';
} else {
document.getElementById('alert-dialog').style.display = 'none';
}
}

Use jQuery to click anywhere and remove 'active' class

I'm having some trouble figuring out how to close a div by clicking anywhere on the screen.
I'm currently toggling an 'active' class in order to display a drop down div, then attempting to remove that class by clicking on the body:
$(document).ready(function () {
$('.navbar a').click(function () {
$(this).next('.navbar-dropdown').toggleClass('active');
});
$(body).click(function() {
if($('.navbar-dropdown').hasClass('active')){
$('.navbar-dropdown').removeClass('active');
}
});
});
<ul class="navbar">
<li>
Link
<div class="navbar-dropdown">
Dropdown Content
</div>
</li>
</ul>
However they are conflicting with each other, so as soon as the class is toggled on, the 'body' click toggles it off at the same time. Have spent some time looking on here and came across this method a few times:
$(document.body).click( function() {
closeMenu();
});
$(".dialog").click( function(e) {
e.stopPropagation();
});
However any attempts to configure this to work correctly seemed to fall on deaf ears!
The click event from the navbar is bubbling up to the body, so both events fire. stopPropagation() is one way to prevent that, but you need to do it in the navbar link's event handler, so it stops that particular event; not in a separate event handler as you had it.
Another change you might consider making is to only assign the body click handler when you need it, instead of firing all the time -- create that handler inside the navbar's click handler, and deactivate it again when it's used:
$(document).ready(function() {
$('.navbar a').click(function(e) {
var myDropdown = $(this).next('.navbar-dropdown');
$('.navbar-dropdown.active').not(myDropdown).removeClass('active'); // close any other open dropdowns
myDropdown.toggleClass('active'); // open this one
$('body').click(function() {
// no need for an if statement here, just use a selector that matches the active elements:
$('.navbar-dropdown.active').removeClass('active');
$('body').off('click'); // cancel the body's click handler when it's used
});
e.stopPropagation(); // prevent the navbar event from bubbling up to the body
});
});
.active {
color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="navbar">
<li>
Link
<div class="navbar-dropdown">
Dropdown Content
</div>
</li>
<li>
Link 2
<div class="navbar-dropdown">
Dropdown Content 2
</div>
</li>
<li>
Link 3
<div class="navbar-dropdown">
Dropdown Content 3
</div>
</li>
</ul>
(If there's a chance you might need more than one separate click event handler on the body, you can namespace the event so you can control which one you're turning off:
$('body').on("click.myNamespace", function() {
// do other stuff
$('body').off("click.myNamespace")
})
I did the exact thing as you and it works for me. Are you sure you don't have any other event listeners attached? Or maybe a z-index on the menu bringing it underneath other elements?
$(document).click(function(e) {
$(".dialog").text('closed')
});
$(".dialog").click(function(e) {
e.target.innerText = 'open';
e.stopPropagation();
});
.dialog {
width: 200px;
height: 200px;
background: antiquewhite;
text-align: center;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="dialog">open</div>
</body>
</html>

Make div clickable, only when anchor is present in div (multiple divs)

Given a basic structure how can I turn a series of divs into links without turning every div into a link? Here's an example:
<div class="boxes">
<div class="box"><p>Some text with a link</p></div>
<div class="box"><p>Some text without a link</p></div>
<div class="box"><p>Some text with a link</p></div>
<div class="box"><p>Some text without a link</p></div>
</div>
And the associated jQuery I'm using to make the divs clickable:
$(document).ready(function() {
if($('.boxes p a').length){
$(".boxes .box").click(function() {
window.open($(this).find("a").attr("href"));
return false;
});
}
});
The problem I'm running into is the click function gets applied to all divs instead of only those with links.
The desired behavior is to only create a fully clickable div only when an anchor element is found.
For the purposes of this use case, the div (.box) is generated dynamically and wrapping the element in an anchor tag (<div> </div>) is not possible.
Fiddle: https://jsfiddle.net/fu8xLg0d/
Because you add event listeners on all the .boxes .box classes, which are all your divs.
Just add something like :
$(".boxes .box").has('a')...
to narrow it to those only containing an a element
JSFiddle
use .parent to solve your purpose:
$(document).ready(function() {
if($('.boxes p a').length){
$("a").parent().parent().click(function() {
window.open($(this).find("a").attr("href"));
return false;
});
}
});
But yes, it can even create a problem so i will say to give a class to your link and then call its parent... :)
Plotisateur just beat me by a minute or two! :P
if($('.boxes p a').length){
$(".boxes .box").has('a').click(function() {
window.open($(this).find("a").attr("href"));
return false;
});
Here's the code anyway: https://jsfiddle.net/fu8xLg0d/1/
You can try this.
$(document).ready(function() {
var anchorbox =$(".boxes p a");
if(anchorbox.length>0){
$(anchorbox).parent().click(function() {
window.open($(this).find("a").attr("href"));
return false;
});
}
});
div (.box) is generated dynamically.
Delegate the click event from the body to the target div and on click on the element check if it has anchor tag. For adding the pointer icon create a separate function which will add the icon to the div only if it has an anchor tag as child
$(document).ready(function() {
// separate function to add pointer only if a is present
addClassToElem();
$("body").on('click', '.box', function() {
if ($(this).find('a').length) {
window.open($(this).find("a").attr("href"));
return false;
}
})
});
function addClassToElem() {
$('.box a').each(function(a, b) {
$(this).parent().addClass('linkIcon')
})
}
.linkIcon {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="boxes">
<div class="box">
<p>Some text with a link</p>
</div>
<div class="box">
<p>Some text without a link</p>
</div>
<div class="box">
<p>Some text with a link</p>
</div>
<div class="box">
<p>Some text without a link</p>
</div>
</div>
This little change, helps you to resolve the issue.
$(document).ready(function() {
if($('.boxes p a').length){
$(".boxes .box").click(function() {
if ($(this).children('p').children('a').length) {
window.open($(this).find("a").attr("href"));
return false;
}
});
}
});
the difference from your code is, additionally add a checking
if ($(this).children('p').children('a').length) {
window.open($(this).find("a").attr("href"));
return false;
}

Detect elements' visibility after adding Display:none using javascript

I have four divs in a main container.
<div id="boxes">
<div class="inner-box"></div>
<div class="inner-box"></div>
<div class="inner-box"></div>
<div class="inner-box"></div>
</div>
After a javascript click event, display: none is added to them to hide. So I want to do something when no elements are visible.
if ($('#boxes').children(':visible').length == 0)
The above code does not seem to be working because it counts the number of visible elements before the click event (even if all the classes have display: none it gives the count 4).
I'm using change(); function for select to toggle the display property.
Demo: http://jsfiddle.net/wnzavyom/1/
Basically every time you process the onclick event you have to then check each item to see if it exhibits the css setting display: none
(Demo)
JAVASCRIPT
$('.inner-box').on("click",function(){
$(this).css("display","none");
var visible = false;
$('.inner-box',$(this).parent()).each(function(){
if($(this).css("display") !== "none") visible = true;
});
if(!visible) alert("All gone");
});
The issue you have is because your boxes are being hidden using fadeOut() which runs asynchronously. This means that when you check the number of :visible elements the animation has not yet finished, so they are still technically visible.
To achieve what you need you should run your code in the callback of the fadeOut() method. Try this:
$('#filter select').change(function () {
$('.inner-box').fadeOut(function() {
if ($('#boxes').children(':visible').length == 0) {
alert('all boxes hidden');
}
});
});
Updated fiddle
HTML
<select id="showhide">
<option>hide</option>
<option>show</option>
</select>
<div id="boxes">
<div class="inner-box">one</div>
<div class="inner-box">two</div>
<div class="inner-box">three</div>
<div class="inner-box">four</div>
</div>
Script
$('.inner-box').hide();
$('#showhide').on('change',function(){
$('.inner-box').toggle();
alert($('#boxes').children(':visible').length);
});
alert($('#boxes').children(':visible').length);
Demo

Hiding a dropdown menu without it flashing with prototype

I have a number of dropdowns and divs that are hidden when the page loads and can be toggled with a click or mouseover, but some of them flash b/c the JavaScript does not run in time. I have their display initially set to block and then I use JavaScript/prototype to find the element and hide it. I have tried loading these "hider" functions using dom:loaded but there is still flashing. This is an example of a dropdown prototype initialization function. From
http://www.makesites.cc/programming/by-makis/simple-drop-down-menu-with-prototype/:
var DropDownMenu = Class.create();
DropDownMenu.prototype = {
initialize: function(menuElement) {
menuElement.childElements().each(function(node){
// if there is a submenu
var submenu = $A(node.getElementsByTagName("ul")).first();
if(submenu != null){
// make sub-menu invisible
Element.extend(submenu).setStyle({display: 'none'});
// toggle the visibility of the submenu
node.onmouseover = node.onmouseout = function(){
Element.toggle(submenu);
}
}
});
}
};
Is there a better way to hide div's or dropdowns to avoid this flashing?
You always run the risk of flicker when you try to hide elements after page load.
I suggest you give the elements in question an inline style like display:none; or a css class with the same setting.
From the class creation syntax used, I take it that you are using something like Prototype version 1.5.x. Here's my take on how I'd do it with that version (it would be nicer to step up to the latest version, of course):
<script type="text/javascript">
var DropDownMenu = Class.create();
DropDownMenu.prototype = {
initialize: function(menuElement) {
// Instead of using 2 listeners for every menu, listen for
// mouse-ing on the menu-container itself.
// Then, find the actual menu to toggle when handling the event.
$(menuElement).observe('mouseout', DropDownMenu.menuToggle);
$(menuElement).observe('mouseover', DropDownMenu.menuToggle);
}
};
DropDownMenu.menuToggle = function (event) {
var menu = DropDownMenu._findMenuElement(event);
if (menu) {Element.toggle(menu);}
};
DropDownMenu._findMenuElement = function (event) {
var element = Event.element(event);
return Element.down(element, 'ul');
}
var toggler = new DropDownMenu('menus');
</script>
And here is some markup to test it with (it may not match yours perfectly, but I think it is similar enough):
<html>
<head>
<title>menu stuff</title>
<style type="text/css ">
/* minimal css */
#menus ul, .menu-type {float: left;width: 10em;}
</style>
</head>
<body>
<h1>Menus</h1>
<div id="menus">
<div class="menu-type">
Numeric
<ul style="display: none;">
<li>1</li><li>2</li><li>3</li><li>4</li>
</ul>
</div>
<div class="menu-type">
Alpha
<ul style="display: none;">
<li>a</li><li>b</li><li>c</li><li>d</li>
</ul>
</div>
<div class="menu-type">
Roman
<ul style="display: none;">
<li>I</li><li>II</li><li>III</li><li>IV</li>
</ul>
</div>
</div>
</body>
</html>
Yoda voice: "Include the prototype.js, I forgot."
Should you want to get rid of inline styling (like I do), give the uls a class like
.hidden {display:none;}
instead, and make the DropDownMenu.menuToggle function do this
if (menu) {Element.toggleClassName(menu, 'hidden');}
instead of toggling the display property directly.
Hope this helps.
Set the display initially to none, then show them as needed. That will get rid of the flashing.

Categories