How to select all elements in the DOM with same class? - javascript

Im trying to implement multilanguage support to a website and for that I need to select all elements that have class="lang" attribute. This is how my Js code looks like
$(function(){
var language = localStorage.getItem('language');
if(language !== null){
//this does not work
$(document).find('.lang').each(function (index, element) {
if($(this).attr('placeholder')!=null){
//change placeholder text
}
$(this).text(arrLang[language][$(this).attr('key')]);
});
}
//this works
$(document).on('click','.translate',function () {
var lang = $(this).attr('id');
$(document).find('.lang').each(function (index, element) {
if($(this).attr('placeholder')!=null){
//change placeholder text
}
$(this).text(arrLang[lang][$(this).attr('key')]);
localStorage.setItem('language',lang);
});
});
});
And this is the html code where Im trying to test this out
<div class="navbar navbar-default navbar-static-top">
<div class="container-fluid">
<div class="navbar-header">
<div class="navbar-brand">
<img alt="brand" src="../img/th-logo.png" height="25px" width="60px" href="Startsite.jsp">
</div>
</div>
<div class="navbar-brand">Studienlaufplan </div>
<button class="navbar-toggle" data-toggle="collapse" data-target=".navHeaderCollapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div class="collapse navbar-collapse navHeaderCollapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="../Startsite.jsp" class="lang" key="tasks" >Aufgaben</a> </li>
<li><a href="../Account.jsp" class="lang" key="account" >Konto</a> </li>
<li>Kanäle </li>
<li>Einstellugen </li>
<li class="dropdown">
Sprache
<ul class="dropdown-menu">
<li>Deutsch</li>
<li>English</li>
</ul>
</li>
<li>Abmelden</li>
</ul>
</div>
</div>
</div>
Im confused about jquery selectors and actually dont know how to use them well. Any help will be appreciated

To get all elements with the specified class name, Try document.getElementsByClassName:-
var x = document.getElementsByClassName("className");
The getElementsByClassName() method is not supported in Internet Explorer 8 and earlier versions.
function myFunction() {
var x = document.getElementsByClassName("example");
x[0].innerHTML = "Hello World!";
x[1].innerHTML = "my first code snippet"
}
<div class="example">First div element with class="example".</div>
<div class="example">Second div element with class="example".</div>
<button onclick="myFunction()">Try it</button>
try it yourself here.

This should do the trick:
$(".lang").each(function() {
const $lang = $(this);
// translate this item's text
});

Related

links, tags a not working on mobile devices

I have 2 links on the site, they work, but if you log in from your phone, they stop working, tag a.
<section class="section section--map" id="map">
<div class="container">
<div class="map">
<h2 class="map__title">
<div>
<i class="fa-solid fa-location-dot"></i>
</div>
<a href="https://dayz.xam.nu/" target="_blank">
map dayz
</a>
</h2>
</div>
</div>
</section>
there is also a problem with the second link
<div class="container__header">
<div class="header__inner">
<div class="header__logo" data-scroll="#intro"></div>
<nav class="nav" id="nav">
<a class="nav__link active" href="#" data-scroll="#about">about</a>
<a class="nav__link" href="#" data-scroll="#services">howtoplay</a>
<a class="nav__link" href="#" data-scroll="#mods">mods</a>
<a class="nav__link" href="#" data-scroll="#updates">updates</a>
<a class="nav__link" href="#" data-scroll="#map">map</a>
<a class="nav__link" href="https://dayzmsk.dayzplay.ru/" target="_blank">shop</a>
</nav>
<a class="btn__discord" href="https://discord.gg/qyUnGSePWf" target="_blank"><img src="../img/dslogosite.png" alt=""></a>
</div>
</div>
almost all links work on js, fast and smooth transition to the section
document.querySelector('.nav').addEventListener("click", (event) => {
if (event.target.getAttribute('href') !== '#') {
return;
}
event.preventDefault();
let elementOffset = 0;
let parent = document.querySelector('.nav');
let menuItem = parent.querySelectorAll('.nav__link');
if(event.target.classList.contains('nav__link')) {
for (let i = 0; i < menuItem.length; i++) {
menuItem[i].classList.remove('active');
}
}
let elementId = event.target.getAttribute('data-scroll');
let element = event.target;
if(elementId && element){
elementOffset = getElementScrollOffset(elementId);
scrollToTop(elementOffset);
element.classList.add('active');
}
});
I tried to give index 999 to elements, tried to remove the target, but it didn’t help, I don’t understand why it works on the computer, but not on the phone
The display block was to blame, if you remove it from the element, everything works. Close.

How can I maintain collapse-state of side bar after page refresh?

In my Sidebar I have included a collapse button to show/hide tabs. Now I want to maintain the collapse-state when refreshing the page: If the form was un-collapsed before refreshing the page, it must stay like this after the refresh. I am new to js. Below is my HTML:
<div class="sidebar">
<li class="mb-1">
<button class="btn btn-toggle align-items-center fa fa-database" data-bs-toggle="collapse"
data-bs-target="#button-1-collapse" aria-expanded="true">
Button-1
</button>
<div class="collapse" id="button-1-collapse" style="">
<ul class="btn-toggle-nav list-unstyled fw-normal pb-1 ">
<li> example-1</li>
<li> example-2</li>
<li> example-3</li>
</ul>
</div>
</li>
<li class="mb-1">
<button class="btn btn-toggle align-items-center fa fa-file-code-o" data-bs-toggle="collapse"
data-bs-target="#button-2-collapse" aria-expanded="true">
Button-2
</button>
<div class="collapse" id="button-2-collapse" style="">
<ul class="btn-toggle-nav list-unstyled fw-normal pb-1 ">
<li> example-1</li>
<li> example-2</li>
<li> example-3</li>
</ul>
</div>
</li>
</ul>
</div>
</li>
</ul>
</div>
Thanks for your help!
After some research, i have what i required. Attaching code part herewith which maybe beneficial to others.
$(function () {
const buttonCollapse1 = $("#button-1-collapse");
const buttonCollapse2 = $("#button-2-collapse");
buttonCollapse1.on("shown.bs.collapse", function () {
sessionStorage.setItem("buttonCollapse1", "show");
});
buttonCollapse2.on("shown.bs.collapse", function () {
sessionStorage.setItem("buttonCollapse2", "show");
});
buttonCollapse1.on("hidden.bs.collapse", function () {
sessionStorage.setItem("buttonCollapse1", "hide");
});
buttonCollapse2.on("hidden.bs.collapse", function () {
sessionStorage.setItem("buttonCollapse2", "hide");
});
const button1 = sessionStorage.getItem("buttonCollapse1");
if (button1 === "show") {
buttonCollapse1.collapse("show");
} else {
buttonCollapse1.collapse("hide");
}
const button2 = sessionStorage.getItem("buttonCollapse2");
if (button2 === "show") {
buttonCollapse2.collapse("show");
} else {
buttonCollapse2.collapse("hide");
}
});

The class i m adding to my element is getting added but upon removal is not getting removed

Okay so my HTML for the navbar is here(I m using boostrap Nav)
<header>
<nav class="navbar navbar-default navbar-fixed-top" role="navigation" id="MyNav">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data- toggle="collapse" data-target="#collapse" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#featured"><h1>Wisdom <span class="subhead">Pet Medicine</span></h1></a>
</div>
<div class="collapse navbar-collapse" id="collapse">
<ul class="nav navbar-nav navbar-right" id="collapse">
<li class="active">Home</li>
<li>Mission</li>
<li>Services</li>
<li>Staff</li>
<li>Testimonials</li>
</ul>
</div>
</div>
</nav>
</header>
The javascript(JQuery) code is here,
$('.navbar-fixed-top').on('activate.bs.scrollspy',function(){
var current= $(this).find('#MyNav li .active a').attr('href');
if(current !== '#featured'){
$('header nav').addClass('inbody');
}
else{
$('header nav').removeClass('inbody');
}
});
Now, the problem is that, whenever i scroll down to a section, the ACTIVE class changes to a different li tag and so the inbody class gets attached to the <nav> element, following the IFCondition. But when i scroll back up the inbody class is not getting removed as per the ELSE condition. Need help.
You have an extra space in selector for li.active
Change:
var current= $(this).find('#MyNav li .active a').attr('href');
^^ // extra space
To
var current= $(this).find('#MyNav li.active a').attr('href');
Your version looks for an active class inside the <li> not an <li> that has that class
What #charlietfl said is correct. However a better solution might be to use the event target instead:
$('.navbar-fixed-top').on('activate.bs.scrollspy',function(ev){
var current = $(ev.target).find('a').attr('href');
...
});
There were two issues with this line of code:
var current= $(this).find('#MyNav li .active a').attr('href');
Your initial select $(this) will be your nav element. You then use .find() which searches for all descendants of the nav element. #MyNav isn't a descendant (its the same element) so the find function won't return anything.
The second issue is "li .active" which will look for elements with the active class that are a descendant of an li element. But you want li elements that have the class "active". In order to get that, don't include a space between them.
The line should look like this:
var current= $(this).find('li.active a').attr('href');

Bootstrap CSS Navigation Active class change onclick

I am having a problem getting the active class to change when next page is clicked. I have tried numerous different variations of scripts that I found on here, but haven't had any luck getting any to work. My project is located here: http://criminallawyerhuntsville.com/proof/.
<script>
$('.navbar-right li').click(function(e) {
$('.navbar-right li.active').removeClass('active');
var $this = $(this);
if (!$this.hasClass('active')) {
$this.addClass('active');
}
e.preventDefault();
});
</script>
</head>
<body>
<div id="wrapper">
<header id="header" style="backface-visibility: hidden; transition: -webkit-transform 0.25s ease-in-out;">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#Navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><img src="images/robertsonlogo.png" height="50px"></a>
</div>
<div class="collapse navbar-collapse" id="Navbar">
<ul class="nav navbar-nav navbar-right">
<li class="active">Home</li>
<li>Domestic Violence</li>
<li>Drug Crime</li>
</ul>
</div>
</div>
</nav>
</header>
Your using jQuery with no $(document).ready() ? change your code to the following for it to even trigger then check the console for errors if any.
<script>
$(document).ready(function(){
$('.navbar-right li').click(function(e) {
$('.navbar-right li.active').removeClass('active');
var $this = $(this);
if (!$this.hasClass('active')) {
$this.addClass('active');
}
e.preventDefault();
});
});
</script>
If you use prevent default you want to prevent the anchor tag to work, so the click have to be on it
This example is if your active class is on the li and not the anchor:
$('.navbar-right li a').click(function(e) {
$('.navbar-right li.active').removeClass('active');
if (!$(this).parent().hasClass('active')) {
$(this).parent().addClass('active');
}
e.preventDefault();
});
as tried here: https://jsfiddle.net/xhgwjxku/

How do I get my twitter bootstrap navbar to close on click?

I am trying to get my navbar to auto collapse on click. Specifically when it is on a mobile device. I do not see why the below code will not work but I believe I maybe have the '.nav navbar-toggle a' wrong.
HTML
<div class="navbar navbar-fixed-top navbar-default" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"></a>
</div>
<div class="collapse navbar-collapse" id="close">
<ul class="nav navbar-nav">
<li class="navtext">ABOUT</li>
<li class="navtext">SERVICES</li>
<li class="navtext">WORK</li>
<li class="navtext">CONTACT</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
Java script (I added this code to the end of bootstrap.js)
function close_toggle() {
if ($(window).width() <= 768) {
$('.nav.navbar-nav a').on('click', function(){
$("#close").click();
});
}
else {
$('.nav.navbar-nav a').off('click');
}
}
close_toggle();
$(window).resize(close_toggle);
The website is speak-design.com
Thank to Hide Twitter Bootstrap navbar on click
I commented first:
('.nav navbar-nav a') should be ('.nav.navbar-nav a') see:
CSS rule to apply only if element has BOTH classes and you should apply your click
for closing on .navbar-collapse if i understand your question well
When i test the above i think i should work with the code shown below.
<script>
function close_toggle() {
if ($(window).width() <= 768) {
$('.nav.navbar-nav a').on('click', function(){
$('.navbar-collapse').collapse('hide');
});
}
else {
$('.nav.navbar-nav a').off('click');
}
}
close_toggle();
$(window).resize(close_toggle);
</script>
NB i think .collapse('hide'); make more sense (more readable) than doing click although the effect will be the same maybe.
Its already doing it. Make sure you added the viewport in your metatags
<meta name="viewport" content="initial-scale=1">
Reference

Categories

Resources