How to toggle Bootstrap 5 accordion component via JavaScript? - javascript

I'm using the accordion component from Bootstrap 5 and I want to toggle the component from my own JavaScript function (toggle in the example below). Preferably without having to include jQuery.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<button onclick="toggle(event)">Toggle Accordion Item #1</button>
<div class="accordion" id="accordionPanelsStayOpenExample">
<div class="accordion-item">
<h2 class="accordion-header" id="panelsStayOpen-headingOne">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapseOne" aria-expanded="true" aria-controls="panelsStayOpen-collapseOne">
Accordion Item #1
</button>
</h2>
<div id="panelsStayOpen-collapseOne" class="accordion-collapse collapse show" aria-labelledby="panelsStayOpen-headingOne">
<div class="accordion-body">
<strong>This is the first item's accordion body.</strong> It is shown by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>
<script>
// Toggle Accordion Item #1
function toggle(event) {
// ???
}
</script>
</body>
</html>
Snippet put together from the examples at https://getbootstrap.com/docs/5.1/getting-started/introduction/ and https://getbootstrap.com/docs/5.1/components/accordion/.

Check out the docs for the collapse component.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<button onclick="toggle(event)">Toggle Accordion Item #1</button>
<div class="accordion" id="accordionPanelsStayOpenExample">
<div class="accordion-item">
<h2 class="accordion-header" id="panelsStayOpen-headingOne">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapseOne" aria-expanded="true" aria-controls="panelsStayOpen-collapseOne">
Accordion Item #1
</button>
</h2>
<div id="panelsStayOpen-collapseOne" class="accordion-collapse collapse show" aria-labelledby="panelsStayOpen-headingOne">
<div class="accordion-body">
<strong>This is the first item's accordion body.</strong> It is shown by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>
<script>
// Toggle Accordion Item #1
function toggle(event) {
var myCollapse = document.getElementsByClassName('collapse')[0];
var bsCollapse = new bootstrap.Collapse(myCollapse, {
toggle: true
});
}
</script>
</body>
</html>

Related

toggleClass Each element One By One jQuery

Problem is that I'm using an array that has more than one element. So, on the toggle, the last class gets passed and functionality given for the last element gets integrated and all starting elements were just added but didn't show any functionality.
I need that each element first to show functionality then toggled to another class.
var arrayOfButtonId = [];
$(".buttons-container").click(function (e) {
var clickedItemId;
// if (e.target !== e.currentTarget) {
clickedItemId = e.target.id;
arrayOfButtonId.push(clickedItemId);
console.log(arrayOfButtonId);
var counter = 0;
arrayOfButtonId.forEach((id) => {
console.log(id, counter++);
setTimeout(() => {
$(".sample-display").toggleClass(id,);
}, 4000);
});
});
For this, In HTML I have Various buttons which can pass the value to js . So that value gets added one by one with some time delay till one function shows its work properly.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Sample HTML</title>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"
/>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
/>
</head>
<div class="card col-md-6 offset-md-3 shadow text-center animate__animated">
THis is for Sample.
</div>
<div
class="
container-fluid
buttons-container
col-md-3
alert-primary
text-dark
rounded
"
>
<!-- Animation for Attention Makers -->
<div class="card col-md-12 my-md-2 py-md-2">
<span class="text-capitalize font-weight-bold text-center"
>Attention Maker</span
>
<input
type="button"
class="btn btn-outline-danger offset-md-1 col-md-10 m-md-3"
value="Flash"
id="animate__flash"
/>
<input
type="button"
class="btn btn-outline-danger offset-md-1 col-md-10 m-md-3"
value="Bounce"
id="animate__bounce"
/>
<input
type="button"
class="btn btn-outline-danger offset-md-1 col-md-10 m-md-3"
value="Tada"
id="animate__tada"
/>
</div>
</div>
<!-- script Start-->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<!-- script End-->
<script src="./js/main.js"></script>
<body></body>
</html>

How do you make a javascript function run on selection from this Bootstrap menu?

I recently found some awesome code for displaying a scrolling menu, but I am at a complete loss as to how to make a function run by selecting it. Any help would be most appreciated. Thank you for your time and patience.
Right now I am just trying to make an alert pop up upon selection.
METHOD 1:
ADD AN ID SHOW ALERT!!! and then in js attach a click handler function:
$('#mymenu').click(function() {
alert("HELLO WORLD");
});
METHOD 2:
There are other possibilities like onclick attribute:
SHOW ALERT!!!
METHOD 3:
OR in the onclick call a function which is defined in js.
SHOW ALERT!!!
<script>
function myfunc(){
alert("HELLO WORLD");
}
</script>
SEE WORKING EXAMPLE OF THE 3 METHODS:
$(document).ready(function() {
$('#mymenu').click(function() {
alert("HELLO WORLD");
});
});
.scrollable-menu {
height: auto;
max-height: 200px;
overflow-x: hidden;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Bootply snippet - Bootstrap Scrollable Dropdown Menu</title>
<meta name="generator" content="Bootply" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="description" content="Bootstrap How to create a scrolling dropdown menu in Bootstrap for large item lists. example snippet for Bootstrap." />
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h2 class="bold">Scrollable Menu</h2>
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">Scrollable Menu <span class="caret"></span>
</button>
<ul class="dropdown-menu scrollable-menu" role="menu">
<li>SHOW ALERT METHOD-1!!!
</li>
<li>SHOW ALERT METHOD-2!!!
</li>
<li>SHOW ALERT METHOD-3 !!!
<script>
function myfunc() {
alert("HELLO WORLD");
}
</script>
</li>
</ul>
</div>
</div>
</div>
</div>
<script type='text/javascript' src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript' src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
</body>
</html>

Can't get Zurb Foundation accordion to work

I'm using Zurb's Foundation, attempting to build a FAQ page using the accordion js. But it's not working and I have no idea why. All the js files are in the js folder. Here's my whole page:
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="css/foundation.css" />
<link rel="stylesheet" href="css/app.css">
<script src="js/vendor/modernizr.js"></script>
</head>
<body>
<div class="row row-padding">
<div class="small-12 columns">
<h1>FAQ:<h1>
</div>
</div>
<div class="row row-padding small-12">
<ul class="accordion" data-accordion>
<li class="accordion-navigation">
Question
<div id="panel13a" class="content">
Answer
</div>
</li>
</ul>
</div>
<script>
$('#myAccordionGroup').on('toggled', function (event, accordion) {
console.log(accordion);
});
</script>
<script src="js/vendor/jquery.js"></script>
<script src="js/foundation/foundation.js"></script>
<script src="js/foundation/foundation.accordion.js"></script>
</body>
</html>
I'm brand new to HTML websites, so sorry if it's something stupid.
You are targeting your accordion with an id that doesn't exist in your HTML.
You'll need to add the id to your HTML like this:
<div class="row row-padding small-12">
<ul id="myAccordionGroup" class="accordion" data-accordion>
<li class="accordion-navigation">
Question
<div id="panel13a" class="content">
Answer
</div>
</li>
</ul>
</div>
Also change the order of your scripts so that your custom accordion loads after everything else.
<script src="js/vendor/jquery.js"></script>
<script src="js/foundation/foundation.js"></script>
<script src="js/foundation/foundation.accordion.js"></script>
<script>
$(document).foundation();
$('#myAccordionGroup').on('toggled', function (event, accordion) {
console.log(accordion);
});
</script>
Here is a working CodePen: http://codepen.io/anon/pen/jPmRyB
You forgot about $(document).foundation();
http://foundation.zurb.com/docs/javascript.html - Initialize Foundation

specfic element cannot be selected with jquery

I am making a website, I want to change the content of the page on clicking certain sections. I have CSS, HTML, JS is seperate files. I am a noob. Using jquery I am getting an alert when I give the tag("*")to select all elements, but for the life of me I am not able to select a specific div. all divs are unique but I really don't why the query cannot select the particular divs.
$('*').click(function()
{ alert("The paragraph was clicked.");
});
----> working
but this is not
$('#topbar').click(function(){
alert("The paragraph was clicked.");
});
here is the entire code:
<!doctype html>
<html>
<head>
<title>dear C</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" type="text/css" href="bbc.css">
</head>
<link href='http://fonts.googleapis.com/css?family=Slabo+27px' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Libre+Baskerville:400italic' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Quicksand' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="jquery-2.1.3.min.js">
</script>
<script type="text/javascript" src="resume.js">
</script>
<body>
<div id="container">
<div id="topbar">
<div id="logo">
</div>
<div id="contact">
<div id="facebook">
</div>
<div id="mail">
</div>
<div id="blog">
</div>
</div>
<div id="name"> Dip Ranjan Chatterjee</div>
</div>
<div id="bottom">
<div id="sidebar">
<div id="about">About</div>
<div id="border"></div>
<div id="edu">Education</div>
<div id="border2"></div>
<div id="prof">Professional Exp.</div>
<div id="border3"></div>
<div id="portfolio">Portfolio</div>
</div>
<div id="contents"><p>
<p>Feel free to drop me a mail or message, if you need to get in touch with me.</p>
</div>
</div>
</body>
Also note i have CSS html and JS all in seperate files. In the JS file i am putting the jquery.
Make sure that you dont have multiple divs with the same id(#topbar in that case), and you are adding the listener after the document is loaded.
$(document).ready(function(){
$('#topbar').click(function(){
alert("The paragraph was clicked.");
});
});
Show all your HTML code
The identifier id="topbar" exist?
id="topbar" is unique in the HTML?
You are declaring the script after loading the HTML?
<div id="topbar">Go</div>
<div id="topbar2">Go2</div>
<script type="text/javascript">
$('#topbar').click(function(){
alert("The paragraph was clicked.");
});
</script>
<!-- works -->

Semantic UI Dropdown can't work

I have tried to deal with this problem for 2 days, but I still can't get the JavaScript of Semantic UI to work. This is my all code. My jQuery is not very good. I have read a lot, but it doesn't work.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0,
minimum- scale=0.5, maximum-scale=2.0,
user-scalable=yes" /> <!--自适应-->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" charset="utf-8">
<title>后台管理系统</title>
<link rel="stylesheet" type="text/css" href="css/semantic.css">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.address.js"></script>
<script type="text/javascript" src="js/semantic.js"></script>
<style type="text/css">
.diymenu{background-color: blue;margin: 0px 0px 0px 0px; padding-top:0px;}
body{margin: 0px 0px 0px 0px;font-family: 微软雅黑;}
</style>
<script type="text/javascript">
$(document).ready(function(){
$('#drop').click(function(){
$('#drop').dropdown('show');
});
});
</script>
</head>
<body >
<!--导航栏 -->
<div class="ui blue inverted menu">
<a class="active item"><i class="home icon"></i>主页</a>
<div class="right menu">
<a class="item"><i class="mail icon"></i>消息
<div class="ui black circular label">2</div></a>
<a class="item">
</a>
</div>
</div>
<div class="ui dropdown item" id="drop">
More <i class="dropdown icon"></i>
<div class="menu">
<a class="item"><i class="edit icon"></i>编辑个人信息</a>
<a class="item"><i class="globe icon"></i>选择语言</a>
<a class="item"><i class="settings icon"></i>账户设置</a>
</div>
</div>
</body>
</html>
From the docs at http://semantic-ui.com/modules/dropdown.html#/usage, you should initialize your dropdown with Javascript (no further jquery code required):
$('.ui.dropdown').dropdown();
See also http://jsfiddle.net/fd8qfyra/1/ i think there is no problem.
After researching through blogs, youtube and more I found the answer, implemented it and given me the collapsing dropdown functionality with Semantic UI
Put the CSS and semantic.js link inside the header instead of the body
Give the select an ID
3.Initialize the ID with with dropdown only:
$('#gender-select').dropdown();

Categories