Disable button 1 Section when click on button 2 - javascript

Have multiple buttons and sections associated with those buttons in the Elementor page builder.
What I am trying to achieve is when page loads, we can only see buttons and section will toggle when someone clicks on the button.
I have managed to achieve that, but when clicking on second button, button 1 section should hide and button 2 section should display.
Here is the w3 schools link for my project
jQuery(document).ready(function( $ ){
var hbtn = $(".coursesBtn");
var hcon = $(".coursesSection");
hcon.hide();
hbtn.click(function(e) {
var index = hbtn.index(this)
$(hcon).eq(index).slideToggle("slow");
e.preventDefault();
});
});
jQuery(document).ready(function( $ ){
var hbtn = $(".videosBtn");
var hcon = $(".videosSection");
hcon.hide();
hbtn.click(function(e) {
var index = hbtn.index(this)
$(hcon).eq(index).slideToggle("slow");
e.preventDefault();
});
});

You can use onclick for buttons for example
<button class="btn1" onclick="f1()">BUTTON1</button>
and add the function to toggle in f1()

Here is a quick example, the idea is to hide the other sections first, and show the section that you want to be displayed;
$(document).ready(function($) {
$('.btn1').click(function() {
$('.section').hide();
$('.section1').show();
})
$('.btn2').click(function() {
$('.section').hide();
$('.section2').show();
})
$('.btn3').click(function() {
$('.section').hide();
$('.section3').show();
})
})
.section {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
.section2 {
background-color: lightgreen;
}
.section3 {
background-color: orange;
}
<button class="btn1">BUTTON1</button>
<button class="btn2">BUTTON2</button>
<button class="btn3">BUTTON3</button>
<div class="section section1">
This is Section1.
</div>
<div class="section section2">
This is Section2.
</div>
<div class="section section3">
This is Section3.
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>

Add a new class for each button (.btn) and section (.section) and use these as in the code below. You can have as many buttons and sections as you want and the code below will work without any modification:
var hbtn = $(".btn");
var hcon = $(".section");
hcon.hide();
hbtn.click(function(e) {
var index = hbtn.index(this);
hcon.hide() //OR hcon.filter(':visible').slideToggle("slow")
.eq(index).slideToggle("slow");
});
DEMO
$(document).ready(function( $ ){
var hbtn = $(".btn");
var hcon = $(".section");
hcon.hide();
hbtn.click(function(e) {
var index = hbtn.index(this);
hcon.hide() //OR hcon.filter(':visible').slideToggle("slow")
.eq(index).slideToggle("slow");
});
});
.section1 {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
.section2 {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn1 btn">BUTTON1</button>
<button class="btn2 btn">BUTTON2</button>
<div class="section1 section">
This is Section1.
</div>
<div class="section2 section">
This is Section2.
</div>

Related

how to fix onClick button for append functions?

Here I work on a project where I want to implement open and close buttons but I am not able to do
currently, it's a close button for both, I need to add separate open and close buttons so that when the user clicks on open then it's open and when someones click on close then it should close properly also when I click continuously close then buttons freezes for sometime
Here is the demo of my JSFiddle Demo
please check the js Fiddle demo where buttons doesn't work properly
Here is the code
function createItem(item) {
var elemId = item.data("id");
var clonedItem = item.clone();
var newItem = $(`<div data-id="${elemId}"></div>`);
newItem.append(clonedItem);
newItem.appendTo('.item-append');
}
function countSaveItems() {
$('.count').html($(".item-append div.item-save[data-id]").length);
}
$('.item-all .item-save').click(function() {
$(this).toggleClass('productad')
window.localStorage.setItem('test_' + this.dataset.id, $(this).hasClass('productad'));
});
$('.item-all .item-save').each(function() {
var id = 'test_' + $(this).data("id");
$(this).append(`<button class='close'>Close</button>`);
if (localStorage.getItem(id) && localStorage.getItem(id) == "true") {
$(this).addClass('productad');
createItem($(this));
countSaveItems();
}
});
$(".item-all .item-save").click(function() {
var elemId = $(this).data("id");
var existing = $(`.item-append div[data-id="${elemId}"]`);
if (existing.length > 0) {
existing.remove();
} else {
createItem($(this));
}
countSaveItems();
});
$(".item-append").on("click", ".close", function() {
var id = $(this).parent().data("id");
localStorage.removeItem(`test_${id}`);
$(`.item-save[data-id='${id}']`).removeClass('productad');
$(this).parent().remove();
countSaveItems();
});
.item-save {
position: relative;
display: block;
font-size: 14px;
margin: 5px;
padding: 5px;
background: #a5a5a5;
float: left;
text-align: center;
cursor: pointer;
}
.productad {
background: red;
color: #eee
}
.count {
display: block;
background: #cbcbcb;
float: left;
font-size: 15px;
padding: 5px 18px;
margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='item-all'>
<div class='item-save' data-id='123'>
Save1
</div>
<div class='item-save' data-id='124'>
Save2
</div>
<div class='item-save' data-id='125'>
Save3
</div>
<div class='item-save' data-id='126'>
save4
</div>
</div>
<div class='item-append'>
</div>
<div class='count'>0</div>
Any Kind of help or suggestion is highly appreciated
To do the effect you need to add the open button into the HTML because that will be static, then switch between "Open" and "Close" when the user clicks into the "Open" or close the item, also needs to fix the local storage instead of removing in the close button just switch the value to false and validate based on that value. check the following code to see if that is what you are looking for:
function createItem(item){
var elemId = item.data("id");
var clonedItem = item.clone();
var newItem = $(`<div data-id="${elemId}"></div>`);
newItem.append(clonedItem);
clonedItem.children('.open').remove();
clonedItem.append(`<button class='close'>Close</button>`);
newItem.appendTo('.item-append');
}
function countSaveItems(){
$('.count').html($(".item-append div.item-save[data-id]").length);
}
$('.item-all .item-save').click(function() {
var id = $(this).data("id");
var lsId = `test_${id}`;
$(this).toggleClass('productad');
if (!$(this).hasClass('productad')){
window.localStorage.setItem(lsId, false);
$(this).children(".open").html("Open");
createItem($(this));
}else{
window.localStorage.setItem(lsId, true);
$(this).children(".open").html("Close");
$(`.item-append div[data-id='${id}']`).remove();
}
countSaveItems();
});
$('.item-all .item-save').each(function() {
var id = 'test_' + $(this).data("id");
if (localStorage.getItem(id) && localStorage.getItem(id) == "true") {
$(this).addClass('productad');
createItem($(this));
}
countSaveItems();
});
$(".item-all .item-save").click(function() {
var elemId = $(this).data("id");
var existing = $(`.item-append div[data-id="${elemId}"]`);
if (existing.length > 0){
existing.remove();
}else{
createItem($(this));
}
countSaveItems();
});
$(".item-append").on("click", ".close", function() {
var id = $(this).parent().data("id");
window.localStorage.setItem(`test_${id}`, false);
$(`.item-save[data-id='${id}']`).removeClass('productad');
$(`.item-save[data-id='${id}']`).children(".open").html("Open");
$(this).parent().parent().remove();
countSaveItems();
});
.item-save {
position: relative;
display: block;
font-size: 14px;
margin: 5px;
padding: 5px;
background: #a5a5a5;
float: left;
text-align: center;
cursor: pointer;
}
.productad {
background: red;
color: #eee
}
.count {
display: block;
background: #cbcbcb;
float: left;
font-size: 15px;
padding: 5px 18px;
margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='item-all'>
<div class='item-save' data-id='123'>
Save1 <button class='open'>Open</button>
</div>
<div class='item-save' data-id='124'>
Save2 <button class='open'>Open</button>
</div>
<div class='item-save' data-id='125'>
Save3 <button class='open'>Open</button>
</div>
<div class='item-save' data-id='126'>
Save4 <button class='open'>Open</button>
</div>
</div>
<div class='item-append'></div>
<div class='count'>0</div>

click a button to delete itself and its parent div

--- UPDATED QUESTION ---
Thanks for all the answers. I wrote the JS code to delete the parent div when clicking its corresponding button in my JS PRACTICE!!!
However, the same JS code does not work in my real JS project where all the parent div are created dynamically. The complete code can be found below.
There is no error but the JS code just does not work. Any ideas?
BELOW IS THE SIMPLIFIED **REAL JS PROJECT ** COMPLETE CODE
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Imgs</title>
<style type="text/css">
.container {
width: 100%;
}
.display-area {
width: 100%;
height: auto;
display: flex;
justify-content: flex-start;
flex-wrap: wrap;
}
img {
max-width: 100%;
}
.image-preview {
width: 80%;
min-height: 300px;
border: 2px dashed #dddddd;
display: block;
/*default text*/
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
color: #cccccc;
}
.newbtns {
border: 0;
background: lightgrey;
text-shadow: 1px 1px 1px white;
border: 1px solid #999;
position: absolute;
display: block;
}
</style>
</head>
<body>
<div class="container">
<div id='inputFiles'><input type="file" class="file" name="image_uploads" accept="image/png, image/jpeg, image/jpg"
multiple></div>
<div class="display-area" id='imgDisplay'>
</div>
<div id="defaultContent">
<p>No images</p>
</div>
<button type="button" value="Reload page" onclick="window.location.reload()">Reload Page</button>
</div>
</div>
</body>
<script>
var input = document.querySelector('input');
var uploadBox = document.getElementById('uploadBox');
var defaultContent = document.getElementById('defaultContent');
var imgDisplay = document.getElementById('imgDisplay')
//upload & preview
input.addEventListener('change', function () {
var imgFiles = input.files;
defaultContent.style.display = 'none';
for (var i = 0; i < imgFiles.length; i++) {
var imgDiv = document.createElement('div');
imgDiv.className = 'imgBox';
imgDiv.id = 'box' + i;
imgDiv.style.width = "20%";
var images = document.createElement('img');
images.src = URL.createObjectURL(imgFiles[i]);
var newbtn = document.createElement("button");
newbtn.type = "button";
newbtn.className = "newbtns";
newbtn.innerHTML = "X";
newbtn.style.color = "orange";
newbtn.style.background = 'red';
newbtn.id = 'newbtn' + i;
imgDiv.appendChild(newbtn);
imgDiv.appendChild(images);
imgDisplay.appendChild(imgDiv);
}
});
allButtons = document.getElementsByTagName('button');
for (var n = 0; n < allButtons.length; n++) {
if (allButtons[n].getAttribute('id') === 'newbtn' + n) {
allButtons[n].onclick = function () {
this.parentNode.parentNode.removeChild(this.parentNode);
}
} else { };
}
</script>
</html>
you can do something like this:
const buttonOne = document.getElementById('btn1');
const buttonTwo = document.getElementById('btn2');
buttonOne.addEventListener("click", () => deleteElementAndThisChildNodes('box1'))
buttonTwo.addEventListener("click", () => deleteElementAndThisChildNodes('box2'))
function deleteElementAndThisChildNodes(parentId) {
document.getElementById(parentId).remove()
}
To each of your button elements add onclick="DeleteParent(this)" then outside of your dynamic divs include the following:
<script type="text/javascript">
function DeleteParent(button){
button.parentElement.remove();
}
</script>
You can do this:
const display = document.getElementById("imgdisplayarea");
display.addEventListener("click", e => {
if(e.target.tagName === 'BUTTON'){
//if an element within a display div for a button, remove your father
e.target.parentNode.remove();
}
});
Here is a very simple example that works exactly how you want it (based on your question):
function disable() {
document.getElementById("demo").style.display = "none";
}
<div id="demo">
<button onclick="disable()">
Click Me
</button>
<h3>
This is part of the div
</h3>
</div>

Click toggle with multiple targets

I have a two images and when you click on one, text (relevant to image) slides into view below the image. Currently the method for closing/toggling the text is to click on the image again.
If I click on the second image while the text on the first image is still visible, it closes the text. I then have to click on the second image again to see its text content appear.
I'd like to be able to click on the second image and either the text content just swaps OR it closes the text for the first image and opens the text for the second image (in just one click, not two).
Any input appreciated!
I have a fiddle here
JS:
var teamMember = document.getElementsByClassName("team-member");
var teamRow = document.getElementsByClassName("team-row");
var bioContainer = $( "<div class='container' id='bio-container'></div>" );
$(bioContainer).hide();
$(teamMember).click(function() {
$(this).toggleClass('member-selected');
$('.team-grid').toggleClass('member-active');
$(bioContainer).html("");
var thisBio = $(this).find(".team-bio");
var thisRow = $(this).parent(teamRow);
$(thisRow).after(bioContainer);
var bioHTML = $(thisBio).html();
$height = $(thisBio).outerHeight(true)
$(bioContainer).css('height', $height);
$(bioContainer).slideToggle( "slow", function() {
$(this).html(bioHTML);
});
});
HTML:
<section class="team-grid">
<div class="team-row">
<div class="col-sm-6 team-member">
<img src="https://www.catster.com/wp-content/uploads/2017/11/A-Siamese-cat.jpg">
<div class="team-bio">
<div class="team-bio-inner">
JOHN'S Bio
</div>
</div>
</div>
<div class="col-sm-6 team-member">
<img src="https://r.hswstatic.com/w_907/gif/tesla-cat.jpg">
<div class="team-bio">
<div class="team-bio-inner">
SALLY'S Bio
</div>
</div>
</div>
</div>
</section>
CSS:
.col-sm-6 {
width:50%;
float:left;
}
img {
width:100%;
height:200px;
object-fit:cover;
cursor:pointer;
}
.close-bio {
color:pink;
font-weight:bold;
}
.team-bio {
visibility: hidden;
padding: 80px 20%;
position: fixed;
top: 0;
left: 0;
width: 100%;
}
#bio-container {
background: #666;
width: 100%;
max-width: none;
position: relative;
float: left;
padding: 25px;
color:#fff;
font-size:20px;
}
Please check this answer,
Js Fiddle
var teamMember = document.getElementsByClassName("team-member");
var teamRow = document.getElementsByClassName("team-row");
var bioContainer = $( "<div class='container' id='bio-container'></div>" );
var bioContainerExpanded = false;
$(bioContainer).hide();
$(teamMember).click(function() {
if(bioContainerExpanded){
$(bioContainer).slideToggle( "slow", function() {});
bioContainerExpanded = false;
}
$('.team-grid').toggleClass('member-active');
// Resets bioContainer html to blank
$(bioContainer).html("");
$(this).toggleClass('member-selected');
// Assign 'this' team bio to variable
var thisBio = $(this).find(".team-bio");
// Assign 'this' row to variable (find teamRow parent of this teamMember)
var thisRow = $(this).parent(teamRow);
// Place bio after row
$(thisRow).after(bioContainer);
// Assign 'this' bio html to variable
var bioHTML = $(thisBio).html();
// Dynamically calculte height of the bio including padding
$height = $(thisBio).outerHeight(true)
//assign height to bioContainer before the toggle so that it slides smoothly
$(bioContainer).css('height', $height);
// Slide toggle the bioContainer
$(bioContainer).slideToggle( "slow", function() {
// Insert bioHTML into 'this' bioContainer
$(this).html(bioHTML);
});
bioContainerExpanded = true;
});
.col-sm-6 {
width:50%;
float:left;
}
img {
width:100%;
height:200px;
object-fit:cover;
cursor:pointer;
}
.close-bio {
color:pink;
font-weight:bold;
}
.team-bio {
visibility: hidden;
padding: 80px 20%;
position: fixed;
top: 0;
left: 0;
width: 100%;
}
#bio-container {
background: #666;
width: 100%;
max-width: none;
position: relative;
float: left;
padding: 25px;
color:#fff;
font-size:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="team-grid">
<div class="team-row">
<div class="col-sm-6 team-member">
<img src="https://www.catster.com/wp-content/uploads/2017/11/A-Siamese-cat.jpg">
<div class="team-bio">
<div class="team-bio-inner">
JOHN'S Bio
</div>
</div>
</div>
<div class="col-sm-6 team-member">
<img src="https://r.hswstatic.com/w_907/gif/tesla-cat.jpg">
<div class="team-bio">
<div class="team-bio-inner">
SALLY'S Bio
</div>
</div>
</div>
</div>
</section>

remove siblings class from a href

I'm using owl carousel on a menu.
when I scroll to the div the owl carousel auto slide to the right slides.
now when I arrived in the specific div I add class to the slide (active) but for some reason, I can't remove the active class from the other slides (his siblings).
I think it will be best to check the jsfiddle to understand the problem...
<div class="body">
<div class="menu">
<ul class="owl-carousel owl-theme">
Review
a
b
c
d
e
f
</ul>
</div>
JS file
$('.owl-carousel').owlCarousel({
nav: false,
dots: false,
singleItem: true,
})
var owl = $('.owl-carousel');
owl.owlCarousel();
$( window ).scroll(function() {
let scrollbarLocation = $(this).scrollTop();
let scrollLinks = $('.item');
scrollLinks.each(function(){
let sectionOffset = $(this.hash).offset().top;
if (sectionOffset <= scrollbarLocation){
$(this).siblings().removeClass('active-link');
$(this).addClass('active-link');
let goToSlide = $(this).attr('data-num')
owl.trigger('to.owl.carousel', goToSlide);
}
})
if( scrollbarLocation === 0){
scrollLinks.removeClass('active-link');
owl.trigger('to.owl.carousel', 0);
}
});
check https://jsfiddle.net/jt31h4pr/132/
The problem is that you remove/add active-link class on the same element ( this ). You need to removeClass only on the the element that already has class active-link.
The class active is controlled by the plugin and all the elements that are visible have the active class
See below
$('.owl-carousel').owlCarousel({
nav: false,
dots: false,
singleItem: true,
})
var owl = $('.owl-carousel');
owl.owlCarousel();
$( window ).scroll(function() {
let scrollbarLocation = $(this).scrollTop();
let scrollLinks = $('.item');
scrollLinks.each(function(){
let sectionOffset = $(this.hash).offset().top;
if (sectionOffset <= scrollbarLocation){
$('.active-link').removeClass('active-link'); // added
$(this).addClass('active-link');
let goToSlide = $(this).attr('data-num')
owl.trigger('to.owl.carousel', goToSlide);
}
})
if( scrollbarLocation === 0){
scrollLinks.removeClass('active-link');
owl.trigger('to.owl.carousel', 0);
}
});
.body {
height: 5000px;
}
ul {
padding: 0;
margin: 0;
list-style-type: none;
}
.item {
width: 200px;
height: 70px;
background: red;
margin: 0 15px;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
border-bottom: 4px solid transparent;
}
.active-link {
border-bottom: 4px solid #000;
}
.menu {
position: fixed;
top: 0;
}
section {
width: 100%;
height: 600px;
background: #f8f9fb;
}
#a {
background: lightblue;
margin-top: 200px;
}
#b {
background: lightgreen;
}
#c {
background: tomato;
}
#d {
background: lightpink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.theme.default.css">
<div class="body">
<div class="menu">
<ul class="owl-carousel owl-theme">
Review
a
b
c
d
e
f
</ul>
</div>
<section id="a"></section>
<section id="b"></section>
<section id="c"></section>
<section id="d"></section>
</div>
Look into this fiddle
https://jsfiddle.net/09sLpuwd/1/
What are you doing wrong is trying to remove active class from this and then add active class to the same this, which actualy do nothing.
Insted what I propose is to remove active class from all '.item' emelements and than add it to active one.
As alternative aproach you can store previous item and remove class from it, but I think first way is better.
Hi the problem is with below line
$(this).siblings().removeClass('active-link');
replace it with
$("div.active a").removeClass('active-link');
This was removing and adding class on same time on all so what i did is once i am removing the class from all i am adding it on present elemnt

How do I start with the tab expanded (toggle)?

So I am modifying a web page and there is a table on the bottom of the page that starts minimized. When you click the arrow it opens upward to reveal the table. I am attempting to modify it so that it already starts off opened when the page loads.
HTML Snippet:
<div class="row" id="cp-toggle">
<div class="col-sm-12">
<div class="col-sm-2 col-sm-offset-5 toggle-button">
<a><span class="glyphicon glyphicon-chevron-up"></span></a>
</div>
<div class="col-sm-12" style="height: calc(100% - 25px);max-height: 250px;background-color:#d3d3d3;">
<div style="height: 100%;max-height: 250px;">
<div style="height: 25px;padding-top: 4px;">
<div style="float: left;padding-right: 9px;">
<span> Posts: </span> <span id="posts_count"></span>
</div>
</div>
<div style="overflow-y: scroll;height: 100%;max-height: 225px;">
<table id="result_table" class="table" style="display:table;" >
<thead class="result_thead"></thead>
<tbody class="result_tbody"></tbody>
</table>
</div>
</div>
</div>
</div>
</div>
Javascript:
var control_panel= (function(){
var container = $('#cp-toggle div:first-child');
var btn = $('#cp-toggle div:first-child').find("div").first();
var table_panel = $('#cp-toggle div:first-child div:nth-child(2)').first();
var open_css = "glyphicon-chevron-up";
var close_css = "glyphicon-chevron-down";
var open = function(){
container.find("span").first().switchClass(open_css, close_css);
var h = table_panel.height() + 25;
container.css("top", "calc(100% - "+ h +"px)");
};
var close = function(){
container.find("span").first().switchClass(close_css, open_css);
container.css("top", "calc(100% - 25px)")
};
var isOpen = function(){
return _.contains(container.find("span").first().attr('class').split(/\s+/), close_css);
};
var toggle = function(){
if (isOpen()){
close();
} else {
open();
}
};
btn.on('click', toggle);
return {
open: open,
close: close,
toggle: toggle,
isOpen : isOpen
};
}());
CSS Snippet:
#cp-toggle > div:first-child {
top: calc(100% - 25px);
position: fixed;
z-index: 25;
}
.toggle-button {
height: 25px;
padding-top: 3px;
background-color: #d3d3d3;
border-top-right-radius: 7px;
border-top-left-radius: 7px;
text-align: center;
cursor: pointer;
}
#cp-toggle a {
color: #111;
}
#cp-toggle a:hover {
color: #777;
}
.tab-pane { height: 100%;}
#email-body { height: calc(100% - 80px); }
.body-view { height: 100%; overflow-y: scroll; }
.marked {
color: #ffd700;
}
.marked:hover {
color: #ffd700;
}
I have tried modifying the javascript to call control_panel.open(); at the end. I have tried altering the toggle to start with open();. None of these seem to have any effect on the code. I am not sure if I am looking in the correct area or if I am doing something incorrectly.
Try this (you tried something similar in a comment, but I'll explain in a minute...):
<script>
window.addEventListener('load', function() {
control_panel.open();
});
</script>
The problem with your original attempt...
<script>onLoad=control_panel.open();</script>
... was that it was setting a variable called 'onLoad' with the value of whatever was returned by running the function control_panel.open(), which it did immediately instead of waiting until the page was loaded. Instead, in my example I'm setting an 'onload' listener on the window, so that when the window finishes loading, then it'll run the control_panel.open() function that it is now aware of.

Categories