a function runs multiple times when showing a bootstrap modal. vanilla js - javascript

I have a button that shows a bootstrap modal, it has an onclick attribute set to a function,
The button:
<span style="color:blue;margin-left: 2rem;" data-id="{{student.id}}" id="{{student.id}}"
type="button" data-bs-toggle="modal" data-bs-target="#grade-modal"
onClick="getEnrolledSubjects(this.getAttribute('data-id'))">
<i class="fas fa-plus"></i>
</span>
My javascript function:
function getEnrolledSubjects(id){
var modal = document.getElementById('grade-modal')
modal.addEventListener('shown.bs.modal', function(){
console.log(id)
}
}
at first, it looks fine because it will only log the id once, but when I close the modal and open it again, it will log 2 times, then 3 times, and so on... it goes incrementally. how can i fix this?

as Bootstrap Modal documentation
You can Use event.relatedTarget:
<span style="color:blue;margin-left: 2rem;" data-id="{{student.id}}" id="{{student.id}}" type="button" data-bs-toggle="modal" data-bs-target="#grade-modal">
<i class="fas fa-plus"></i>
</span>
without onClick event
const modal = document.getElementById('grade-modal')
modal.addEventListener('shown.bs.modal', function(event){
const button = event.relatedTarget
const id = button.getAttribute('data-id');
console.log(id)
})

Related

here i want to change play button into pause

this is html
i'm a complete beginner as i started learning js since last two month,
please help me to solve this problem
<h1>Best Song Collection</h1>
<div class="songItem">
<span class="songName">love you zindagi</span>
<span class="btn"><i class="far fa-play-circle playbtn"></i></span>
<span class="btn"><i class="far fa-pause-circle pausebtn"></i></span>
</div>
<div class="songItem">
<span class="songName">love you zindagi</span>
<span class="btn"><i class="far fa-play-circle playbtn"></i></span>
<span class="btn"><i class="far fa-pause-circle pausebtn"></i></span>
</div>
</div>
</div>
js
let pausebtn = document.querySelector(".pausebtn");
let playbtn = document.querySelector(".playbtn")
let btn = document.querySelectorAll(".btn");
function change(element){
if(element.classList==="fa-play-circle"){
element.classList.remove("fa-play-circle");
element.classList.add("fa-pause-circle");
}
}
btn.addEventListner('click',change());
First of all, if you pass a callback function, do not call it. There you need to do it as so btn.addEventListner('click', change);. (Also, there is a typo in addEventListener)
Second of all, I would change the logic of both your HTML and JS. There is no need to keep two spans inside each .songItem div, you can keep only one and just change the class that is responsible for the icon when a user clicks on the button. You will have less code and it will be more readable. Also, you don't need to put a i tag inside a span, you can pass the icons class directly to the span. What is more, it is more convenient to use const instead of let, because you do not intend to change the value of the variables.
You can achieve it by the code written below, I also attach a codepen with a working example.
const pauseIconClassName = 'fa-pause-circle'
const playIconClassName = 'fa-play-circle'
const btns = document.querySelectorAll('.btn')
function onChange (event) {
// get the button elememt from the event
const buttonElement = event.currentTarget
// check if play button class is present on our button
const isPlayButton = buttonElement.classList.contains(playIconClassName)
// if a play button, remove the play button class and add pause button class
if (isPlayButton) {
buttonElement.classList.remove(playIconClassName)
buttonElement.classList.add(pauseIconClassName)
// if a pause button, remove pause button class and add play button class
} else {
buttonElement.classList.remove(pauseIconClassName)
buttonElement.classList.add(playIconClassName)
}
// You can also use .toggle function on classList as mentioned by the person in other answer
}
// query selector all returns a list of nodes, therefore we need to iterate over it and attach an event listener to each button seperatly
btns.forEach(btn => {
btn.addEventListener('click', onChange)
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet"/>
<h1>Best Song Collection</h1>
<div class="songItem">
<span class="songName">love you zindagi</span>
<span class="btn far fa-play-circle"></span>
</div>
<div class="songItem">
<span class="songName">love you zindagi</span>
<span class="btn far fa-play-circle"></span>
</div>
You probably want to toggle the button so I made an example for that. When you press the play button it will show the pause and when you press the pause button it shows play.
When the button is clicked both fa-play-circle and fa-pause-circle are toggled to alter the button icon when clicked.
You made a few mistakes in your code.
The addEventListner() contains a typo. It should be addEventListener()
You store the result of the change() function (which does not exist since it does not return anything) instead of attaching the function as an event handler. So dont call the function.
Your element variable does not contain an element but the event object so you need to call the target or currentTarget property first.
document.querySelectorAll(".btn").forEach(element => element.addEventListener('click', (event) => {
let iElement = event.currentTarget.querySelector('i');
iElement.classList.toggle("fa-play-circle");
iElement.classList.toggle("fa-pause-circle");
}));
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet"/>
<div class="songItem">
<span class="songName">love you zindagi</span>
<span class="btn"><i class="far fa-play-circle playbtn"></i></span>
</div>
<div class="songItem">
<span class="songName">love you zindagi</span>
<span class="btn"><i class="far fa-play-circle playbtn"></i></span>
</div>
pass change to click listener, don't call change function.
btn.addEventListner('click', change);
const pausebtn = document.querySelector(".pausebtn");
const playbtn = document.querySelector(".playbtn");
const btn = document.querySelectorAll(".btn");
function change(element) {
if (element.classList === "fa-play-circle") {
element.classList.remove("fa-play-circle");
element.classList.add("fa-pause-circle");
}
}
btn.addEventListner("click", change);
At first glance, it looks like a syntax issue.
Try to not invoke a function and as args, you should receive an event.
So it will look something like this:
let pausebtn = document.querySelector(".pausebtn");
let playbtn = document.querySelector(".playbtn")
let btn = document.querySelectorAll(".btn");
function change(event){
if(event.target.classList==="fa-play-circle"){
event.target.classList.remove("fa-play-circle");
event.target.classList.add("fa-pause-circle");
}
}
btn.addEventListner('click', change);
EDIT: In HTML you have both buttons for play and pause, you should have just one and change the icon with js toggle.
Semantic tip, use button tag for buttons.

Javascript How to click a class (button) that is inside a class? Do it in Applescript

I'm doing automate in applescript but use Javascript in which I want to click the exact button class ("boost-button") inside a bigger class ("product-item") that contains a string I want. I want to click about 5 of them, each in every ("product-item").
It's like: Do javascript "If getElementByClassName('product-item')[0].innerHTML contains 'The String I Need to Find' then click button class 'boost-button' inside that class"
Because the element number in getElementByClassName('product-item')[0].innerHTML and the getElementByClassName('boost-button')[0].click doesn't go together, they don't click the exact same Class Button.
Does anyone know how to do that? Thanks!
you can use this code
var btn = document.querySelector(".product-item").querySelector(".boost-button")
or just use
var btn = document.querySelector(".product-item .boost-button")
to setup Click Event And Got All Of Your Buttons ...
var btnCollections = document.querySelectorAll(".product-item .boost-button");
btnCollections.forEach(btn => { btn.addEventListener("click", event => EventHandler(event)); });
function EventHandler(event) {
console.log(event.target.textContent)
}
// Auto Click
document.querySelector(".auto-click").addEventListener("click",_=>{
var btnCollections = document.querySelectorAll(".product-item .boost-button");
btnCollections.forEach(btn => btn.click());
} );
<div class="product-item">
<button class="boost-button"> test 1 </button>
<button class="boost-button"> test 2 </button>
<button class="boost-button"> test 3 </button>
</div>
<div class="product-item">
<button class="boost-button"> test 4 </button>
<button class="boost-button"> test 5 </button>
<button class="boost-button"> test 6 </button>
</div>
<button class="auto-click"> Auto Click </button>
Other Way :
and for your click problem read click documentation and use event.target

Write HTML tag inside Javascript text

I have a Javascript function that prints "like" and "Unlike" like this:
$(".liketoggle").click(function () {
$(this).text(function(i, v){
return v === 'Like' ? 'Unlike' : 'Like'
})
});
I have an HTML tag that shows a heart in an tag as:
<i class="fas fa-heart"></i>
How can I show the heart icon next to the like/unlike button. This is the HTML so far:
<button type="submit"
class="btn btn-custom btn-sm liketoggle"
name ="like">Like
</button>
<i class="fas fa-heart"></i>
How I can write to the JS to be included when toggling it?
Similar Function here: http://jsfiddle.net/dFZyv/ but same issue

button is refreshing page instead of calling function

I have a button that is being used to toggle a class on a div to open and close a side menu.
<div id="body-holder" [ngClass]="{'show-nav':isActive}">
<div class="site-wrap">
<button class="toggle-nav" (click)="flipper()">
<i class="fa fa-bars" aria-hidden="true" ></i>
</button>
</div>
</div>
In my component.ts file i have the following code.
isActive: boolean = true;
flipper()
{
this.isActive = !this.isActive;
}
however instead of toggling the class when I click the button the page gets reloaded instead and redirects me to my application homepage.
You have to add preventDefault to your click event in this way:
flipper(event: any)
{
event.preventDefault();
this.isActive = !this.isActive;
}
and in your html code:
<button class="toggle-nav" type="button" (click)="flipper($event)">
<i class="fa fa-bars" aria-hidden="true" ></i>
</button>
Set button type attribute to type="button":
<button type="button" class="toggle-nav" (click)="flipper()">
<i class="fa fa-bars" aria-hidden="true" ></i>
</button>
Setting the button type to type="button" might also solve the problem
<button type="button"
It seems your button is inside a form and causes a submit.
Button inside division or form most of the times have default behavior of loading the page. For that reason, It's better to set type attribute of button as "buton".
<button type="button" class="toggle-nav" onclick="flipper()"> <i class="fa fa-bars" aria-hidden="true" ></i></button>
I think there is mistake in function. You missed to mention "funtion" keyword before you define the function. I tried a sample fiddle: here
<script>
isActive: boolean = true;
function flipper()
{
alert("a");
}
</script>

Angular Modal ng-click does not work

I have made a modal in angular, it pops up great but the exit button doesnt fire to close the modal. It works if the button to open is reclicked but adding a new button inside the modal does not fire the function. Btw there is no bootstrap in this.
<section class="modal" ng-show="showMenu">
<div ng-click="setActive(album)">
<p class="exit" ng-click="modalFunc()"><i class="fa fa-times-circle fa-2x" aria-hidden="true"></i></p>
<h1>{{albumMod.artist}} - {{albumMod.title}}</h1>
<ul class="tracks">
<span><img src={{albumMod.img}}></span>
<li>Album: {{albumMod.album}}</li>
<li>Price: $1.29</li>
</ul>
<form style="display: inline" action="/#cart" method="get">
<button ng-click="setActive(album); cartFunc()" id="{{album.id}}"><a>Add</a></button>
</form>
</div>
</section>
$scope.closeMenu=true;
$scope.showMenu=false;
$scope.showItems=false;
$scope.modalFunc= function(){
$scope.showMenu = !$scope.showMenu;
console.log($scope.selected);
$scope.showItems = !$scope.showItems;
$scope.closeMenu=!$scope.closeMenu;
// console.log($scope.selected.attr("id"));
};
$scope.showMenu flag which you have used to hide popup is not used correctly. When $scope.modalFunc method is called then you negate the value of $scope.showMenu and assigned. So after assignment, $scope.showMenu value will be true.
Now you have used ng-show="showMenu" so your popup will not be hide.
Correct code will be:
1. Set $scope.showMenu = true in the callback which called when popup is opened.
2. $scope.modalFunc= function(){
$scope.showMenu = !$scope.showMenu;
...
}
3. Remove $scope.showMenu=false; since it is not needed.

Categories

Resources