Javascript Toggle a class on clicked class element - javascript

Bit of a basic one, I was unable to to find exactly what I was after on Stack/Google..
Using vanilla javascript, I'm looking to simply toggle a class on the below .barBtn elements, specifically the one I click.
Sample JS Fiddle: https://jsfiddle.net/t376kL4q/
<div class="container">
<div class="btnBar">
<div class="barBtn">Wishlist</div>
<div class="barBtn">Collection</div>
<div class="barBtn">Info</div>
</div>
</div>
<div class="container">
<div class="btnBar">
<div class="barBtn">Wishlist</div>
<div class="barBtn">Collection</div>
<div class="barBtn">Info</div>
</div>
</div>
I have tried adapting others' code found on Stack/Google, e.g. this one which I've JSFiddle'd: https://jsfiddle.net/5rmqucj3/
Where I changed
document.getElementById("mytarget").
to
document.GetElementsByClassName("mytrigger").
(or even 'querySelector')... but I'm not sure how to correctly target the specific class element I click.
Whether or not the above (2nd link) is the best way to go about the JS of this I'm not sure, but generally just after a clean/simple way of achieving this.
Any help would be much appreciated.
Thanks

You need this
var navclick = document.getElementsByClassName("mytrigger");
for (var i = 0; i < navclick.length; i++) {
navclick[i].onclick = function(e) {
this.classList.toggle('myactive');
}
}
.myactive {
background-color: blue;
color: white;
}
<button class="mytrigger">Button
</button>
<div id="mytarget">
<p>Hello</p>
</div>
<button class="mytrigger">Button
</button>

Related

"classList.toggle" doesn't apply styles, but it gets applied manually

I've been creating a night mode for my web page and made a specific class in CSS to apply when it toggles. However it applies to some elements but not for some. But when I write code for each element without classList.toggle it works. I can't figure out what goes wrong. I don't even get errors in console also. I'd really appreciate if you could help me. Thank You.
HTML:
<body id="body">
<div class="top-right">
<button id="nightMode">Night Mode</button>
</div>
<header>
<h2>PHOTOGRAPHER</h2>
<h1>Kylo Ren</h1>
</header>
<section class="pricing" id="price">
<div class="price-section">
<div class="price-card">
<div id="head">
<h3 class="title">Basic</h3>
</div>
<div class="price-sub">
<div class="sub-sec">
<h3>100+ Photos</h3>
</div>
<div class="sub-sec">
<h3>BnW Editing</h3>
</div>
<div class="sub-sec">
<h3>Soft Copy</h3>
</div>
<div class="sub-sec" id="foot">
<h3>$499</h3>
</div>
</div>
</div>
</div>
</section>
<footer id="footer">
<h4>Powered By Kisara Fernando</h4>
</footer>
CSS:
.darkTheme{
background-color: #000;
color: #fff;
}
.lightTheme{
background-color: #fff;
color: #000;
}
JS:
let btn = document.getElementById('nightMode');
let footer = document.getElementById('footer');
btn.addEventListener('click' , changeBg);
function dark(){
btn.classList.toggle("lightTheme");
body.classList.toggle("darkTheme");
footer.classList.toggle("lightTheme");
document.querySelectorAll('#head')[0].classList.toggle("darkTheme");
document.querySelectorAll('#head')[1].classList.toggle("darkTheme");
document.querySelectorAll('#head')[2].classList.toggle("darkTheme");
}
function changeBg(){
dark();
}
None of your element starts with lightTheme set. Every time you click the button, your button and footer will add/remove the lightTheme (but never the darkTheme), and your body will add/remove the darkTheme.
A solution could be just toggle the darkTheme to both the button and the body (the footer will update with the body):
btn.classList.toggle("darkTheme");
body.classList.toggle("darkTheme");
Note: Your lightTheme class would be completely useless here.

Window scroll by only working on one element

I am wondering if someone can help me alter this code so that it resets or works with multiple elements?
On the website below I have this script set up to scroll right by 100vw Using the window.scrollBy(window.innerWidth /1, 0); when the purple box is hovered over.
however I would like it to work with multiple instances and can't seem to get it to work. Is anyone able to help me?
here is my script;
let button = document.getElementById("mybutton");
button.addEventListener("mouseover", () => {
window.scrollBy(window.innerWidth /1, 0);
});
and her is the url: https://ba-site-build.webflow.io/builds/dev-1-hover-slider.
i would really appreciate if anyone can offer any help so much!
Thankyou :)
The problem is that id of elements must be unique, So you can use class instead and in the script loop over elements and add event listener for all of them.
HTML:
<div class="horizontal">
<div class="red">
<div class="scrollThis button">
<div class="purple"></div>
</div>
</div>
<div class="red">
<div class="scrollThis button">
<div class="purple"></div>
</div>
</div>
<div class="yellow"></div>
</div>
JS:
let buttons = document.getElementsByClassName("scrollThis");
for (let item of buttons) {
item.addEventListener("mouseover", () => {
window.scrollBy(window.innerWidth /1, 0); // <-- you can change this amount if you need more than 120px
});
}
I hope this helps you.

AngularJS ng-mouseenter not working in child div

I have been using the AngularJS ng-mouseenter and mg-mouseleave and it has been almost the cause of my death. A quick explanation:
<div class="characterSum">
<div class="avatarContainer" ng-mouseenter="showButton = true" ng-mouseout="showButton = false">
<img ng-src="{{imagePath}}" class="img-thumbnail">
<div class="addImage" ng-show="showButton && (imagePath == 'images/chars/defaultCharacterAvatar.png')">
<button class="btn-btn-default">
Add Character Image
</button>
</div>
</div>
</div>
The CSS properties:
.avatarContainer {
max-width: 150px;
max-height: 150px;
display:inline-block;
float:left;
margin-right:5px;
position:relative;
}
.characterSum {
border: 1px;
min-height:160px;
position:relative;
}
I'm fairly certain it has something to do with my CSS properties. I followed a few instructions to automatically scale an image into a 150 x 150 size so that might explain my CSS properties for those wizards. Anyway, the reason why I think it has something to do with it is because when I add this:
<div ng-mouseenter="showButton = true" ng-mouseout"showButton = false">Hi</div>
And I add it under the parent class "characterSum", when I mouse over Hi, the button shows. As soon as I add this under the class "avatarContainer" the child div, it stops working. If I wrap the ENTIRE avatarContainer class with this div so:
<div ng-mouseenter="showButton = true" ng-mouseout"showButton = false">
HI
<div class="avatarContainer"> ......... </div>
</div>
It only shows the button when I go near hi. I added $scope.$watch on showButton to console.log('detected') whenever showButton changes and in every scenario, "detected" is never logged when I go over the img or anything EXCEPT FOR when I go over hi
Does anyone have any ideas on what crazy curse I have been put under? Or if not, I'm willing to use any other way of accomplishing this. (Basically want the button to show whenever the img is moused over). And I have already tried directly applying ng-mouseover to the img element to no avail.
You had a typo, you need to use ng-mouseleaveinstead of ng-mouseout
Markup
<div class="characterSum">
<div class="avatarContainer" ng-mouseenter="showButton = true"
ng-mouseleave="showButton = false">
<img ng-src="{{imagePath}}" class="img-thumbnail">
<div class="addImage" ng-show="showButton && (imagePath == 'images/chars/defaultCharacterAvatar.png')">
<button class="btn-btn-default">
Add Character Image
</button>
</div>
</div>
</div>

How to get DIV ID on click

I am new to javascript and couldnt find answer online (I feel like its out there since this seems pretty simple thing, I might not be using the right search terms though)
I am working with the code in this jfiddle:
http://jsfiddle.net/ApoG/f7qqq6k2/4/
$('.item').click(function(){
if( document.getElementById("one").style.display != "none") {
document.getElementById("one").style.display = "none";
} else {
document.getElementById("one").style.display = "block";}
var $this = $(this),
tileStyle = $this.hasClass('big') ? { width: 50, height: 50} : { width: 170, height: 110};
$this.toggleClass('big');
$this.find('.item-content').stop().animate( tileStyle );
$container.isotope( 'reLayout' )
});
When you click a div, it takes the 'item' class and changes its properties.
My goal is to have image or one type of text in a widget when its small and another text or image when its expanded on click. I am going to achieve that by changing div custom properties when its clicked using an if statement in my javascript. (right now testing with changes to display)
My questions is...since 'item' class is selected on click, how can I get the DIV ID on click? (right now I hard coded div id)
Thank you.
With JQuery:
$('div').click(function(){
alert(this.id);
});
JSFiddle Demo, with your full code
With Pure JS:
var div = document.getElementsByTagName("div");
for(var i=0; i<div.length; i++){
div[i].onclick = function(){
alert(this.id);
}
}
JSFiddle Demo
Thank you for the toggle tip. I used that to make my code work and show different things in the box depending on the click of the div.
Here is what I ended up doing:
https://jsfiddle.net/ApoG/z3x6hqLe/
<script>
function toggleText1() {
$('#one_one').toggle();
$('#one_two').toggle();
}
function toggleText2() {
$('#two_one').toggle();
$('#two_two').toggle();
}
</script>
<div id="container">
<div class="item">
<div id=one style=display:"none" class="item-content" onclick="toggleText1()">
<div id=one_one class="text" >Show More</div>
<div id=one_two class="text" style="display:none">Show Less</div>
</div>
</div>
<div class="item">
<div id=two style=display:"none" class="item-content" onclick="toggleText2()">
<div id=two_one class="text" >Show More</div>
<div id=two_two class="text" style="display:none">Show Less</div>
</div>
</div>
<div class="item">
<div id=three style=display:"none" class="item-content"></div>
</div>
</div>
I am definitely sure there is a more optimal way to define all the toggle but as I mentioned earlier I am a complete newb so hopefully with more tinkering I will figure that one out.

Selecting a parent element (without using Jquery)

I just need to access the parent div where I have a button changing his siblings divs.
A code example can explain better:
<div class="parent"> <!-- This is structure repeats N times -->
<div class="divToToggleVisiblity divA">trololo A</div>
<div class="divToToggleVisiblity divB">trololo B</div>
<button onClick="toggleThem(this)">This button will toggle above divs</button>
</div>
function toggleThem(a){ // something like this, BUT without Jquery
$(a).closest(".parent").find(".divA").hide();
}
That's what parentNode is for:
a.parentNode.querySelectorAll('.divA');
function toggleThem(elem) {
elem.parentNode.getElementsByClassName('divA')[0].style.display = 'none';
}

Categories

Resources