Rearrange HTML Focused Tab's Row on button click - javascript

I'm porting a program from XAML/C# to HTML/CSS/JavaScript.
I have tabbed sections which rearrange the focused tab's row to the bottom when clicked. This is automatically performed by the TabControl in XAML.
XAML/C#
General Focused
Video Focused
HTML/CSS/JavaScript
How can I do the same with JavaScript?
I'm using this script https://www.w3schools.com/w3css/w3css_tabulators.asp
// Display Tab Section
function OpenTab(tabName) {
var i;
var x = document.getElementsByClassName("tabSection");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
document.getElementById(tabName).style.display = "block";
}
.btnTab {
width: 33.33%;
display: block;
float: left;
background: #020f31;
color: #fff;
padding: 0.2em;
border-top: 1px solid #0080cb;
border-right: 1px solid #0080cb;
border-bottom: none;
border-left: 1px solid #0080cb;
cursor: pointer;
}
<!-- Tabs -->
<div id="sectionTabs">
<button class="btnTab" onclick="OpenTab('General')">General</button>
<button class="btnTab" onclick="OpenTab('Stream')">Stream</button>
<button class="btnTab" onclick="OpenTab('Display')">Display</button>
<button class="btnTab" onclick="OpenTab('Video')">Video</button>
<button class="btnTab" onclick="OpenTab('Audio')">Audio</button>
<button class="btnTab" onclick="OpenTab('Subtitles')">Subtitles</button>
</div>
<!-- Sections -->
<div id="General" class="tabSection">
General ...
</div>
<div id="Stream" class="tabSection" style="display:none">
Stream ...
</div>
<div id="Display" class="tabSection" style="display:none">
Display ...
</div>
<div id="Video" class="tabSection" style="display:none">
Video ...
</div>
<div id="Audio" class="tabSection" style="display:none">
Audio ...
</div>
<div id="Subtitles" class="tabSection" style="display:none">
Subtitles ...
</div>
Fiddle Link

Well if you can change markup a little bit like wrapping the first row and second row of the buttons on different div...
Also try to avoid inline javascript and use data-attributes here
Steps:
create a new array instance from iterable object y usinf Array.from
add a click event on all the buttons using addEventListener
hide all the elements containing tabSection class and also remove active class from all the buttons using for loop.
get the data-tab value from clicked button and set display:block to the respected tab and also add active class to the current button.
now for switching the .first and .second div up and down use insertBefore inside the if condition to compare the index of the clicked button
var x = document.getElementsByClassName("tabSection");
var y = document.getElementsByClassName("btnTab");;
var a = document.querySelector(".first");
var b = document.querySelector(".second")
var p = document.getElementById("sectionTabs");
Array.from(y).forEach(function(elem, index) {
elem.addEventListener("click", function() {
for (var i = 0; i < x.length; i++) {
x[i].style.display = "none";
y[i].classList.remove("active");
}
var tab = this.getAttribute("data-tab");
document.getElementById(tab).style.display = "block";
this.classList.add("active");
if (index < 3) {
p.insertBefore(b, p.childNodes[0])
} else {
p.insertBefore(a, p.childNodes[0])
}
})
})
.btnTab {
width: 33.33%;
display: block;
float: left;
background: #020f31;
color: #fff;
padding: 0.2em;
border-top: 1px solid #0080cb;
border-right: 1px solid #0080cb;
border-bottom: none;
border-left: 1px solid #0080cb;
cursor: pointer;
outline: none;
}
.btnTab.active {
background: red;
}
<!-- Tabs -->
<div id="sectionTabs">
<div class="first">
<button class="btnTab" data-tab="General">General</button>
<button class="btnTab" data-tab="Stream">Stream</button>
<button class="btnTab" data-tab="Display">Display</button>
</div>
<div class="second">
<button class="btnTab active" data-tab="Video">Video</button>
<button class="btnTab" data-tab="Audio">Audio</button>
<button class="btnTab" data-tab="Subtitles">Subtitles</button>
</div>
</div>
<!-- Sections -->
<div id="General" class="tabSection" style="display:none">
General ...
</div>
<div id="Stream" class="tabSection" style="display:none">
Stream ...
</div>
<div id="Display" class="tabSection" style="display:none">
Display ...
</div>
<div id="Video" class="tabSection">
Video ...
</div>
<div id="Audio" class="tabSection" style="display:none">
Audio ...
</div>
<div id="Subtitles" class="tabSection" style="display:none">
Subtitles ...
</div>
Reference Link:
Array.from
forEach()
element.addEventListener
element.classList
element.style
node.insertBefore

This can be achieved by adding a bit more code to OpenTab().
First of all, to check whether a button in the top row or bottom row was pressed, you may add classes row1 to the first row of buttons and row2 to the second row. Then, you can check which button was pressed in OpenTab() by passing in this as an additional parameter: onclick="OpenTab(this, 'General').
With these changes to HTML, the javascript can be changed to change the button pressed into account. In the code below, each if statement checks that the current button is in a particular row with elem.classList.contains("rowX") and that the row is the top row with parent.firstElementChild.classList.contains("rowX"). It then loops through the number of tabs in the row (amount of tabs can vary) and places them in the beginning of the #sectionTabs div.
function OpenTab(elem, tabName) { // Note that `elem` is where `this` is passed
// Your original code
var i;
var x = document.getElementsByClassName("tabSection");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
document.getElementById(tabName).style.display = "block";
// Additional code
row1_elem = document.getElementsByClassName("row1"); // initially top row
row2_elem = document.getElementsByClassName("row2"); // initially bottom row
parent = document.getElementById("sectionTabs");
// check that button in top row was clicked
if (elem.classList.contains("row1") == 1 && parent.firstElementChild.classList.contains("row1") == 1) {
// move elements from bottom row up
for (var j = 0; j < row2_elem.length; j++) {
parent.insertBefore(row2_elem[row2_elem.length-1], parent.firstChild);
}
// check that button in top row was clicked
} else if (elem.classList.contains("row2") == 1 && parent.firstElementChild.classList.contains("row2") == 1) {
// move elements from bottom row up
for (var j = 0; j < row1_elem.length; j++) {
parent.insertBefore(row1_elem[row1_elem.length-1], parent.firstChild);
}
}
}
A jsfiddle is also available:
https://jsfiddle.net/o687eLyb/
Note that you could also wrap the rows into separate divs with IDs rowX and use slightly different logic to check which row was pressed; however, this answer has the benefit that it keeps HTML structure the same.

Related

Two Column Accordion with Separate Full Width Divs

The intension is to have a two column accordion, without limiting the "expand" field to the left or right column. The catch is that there will be multiple on one page. This is already created, but only button 1 is working. With the way my JS is going, it will get very very repetitive - I am looking for assistance with re-writing the JS to be multiple click friendly. Fiddle: https://codepen.io/ttattini/pen/abLzaaY
EDIT: It would also be perfect if one dropdown would close as the next is opened
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="row">
<div id="column">
<button id="button">I am Button #1</button>
<button id="button">I am Button #3</button>
</div>
<div id="column">
<button id="button">I am Button #2</button>
<button id="button">I am Button #4</button>
</div>
</div>
<div id="hidden">
<p id="content"> So here I am #1</p>
</div>
<div id="hidden">
<p id="content"> So here I am #2</p>
</div>
<div id="hidden">
<p id="content"> So here I am #3</p>
</div>
<div id="hidden">
<p id="content"> So here I am #4</p>
</div>
CSS
#hidden {
background: #ccc;
margin-top: 2%;
overflow: hidden;
transition: height 200ms;
height: 0; /* <-- set this */
}
#button {
padding: 10px;
margin-top: 5px;
width:50%;
margin-left: 10%;
cursor: pointer;
}
#row {
display: flex;
}
#column {
flex: 50%;
}
JS
$(function() {
var b = $("#button");
var w = $("#hidden");
var l = $("#content");
b.click(function() {
if (w.hasClass('open')) {
w.removeClass('open');
w.height(0);
} else {
w.addClass('open');
w.height(l.outerHeight(true));
}
});
});
The biggest issue is that you're using IDs when you should be using classes. IDs must be unique to each element in a page. When you repeat an ID, JS will only target the first element using that ID. That's why only the first one is working.
The second issue is that, because of the way the script is written, it will only target a single element. What you need to do is get all the elements you want to target by something like their class name and then loop through them, applying the event listener to each one and its appropriate children.
EDIT: Here is an example from some code I wrote for a page with multiple accordions a few weeks ago in vanilla JS
//Below I establish a counting variable and find all the accordions on the page
const acc = document.getElementsByClassName( 'accordion' );
let i;
//Looping through each accordion
for ( i = 1; i <= acc.length; i++ ) {
//Identify target for the event listener. In this case, a heading for each accordion, which I've numbered e.g. "title-1"
const title = 'title-' + i;
const label = document.getElementById( title );
//Identify target content, in this case a list that has a unique ID e.g. "list-1"
const listNum = 'list-' + i;
const list = document.getElementById( listNum );
//Add event listener to heading that toggles the active classes
label.addEventListener( 'click', function() {
label.classList.toggle( 'accordion--active' );
});
}
Of course, there's more than one way to skin a cat, but this is a working example.
I have tracked the clicked event of each button and showed the corresponding hidden content with the use of data- attribute.
I have used vanilla JavaScipt instead of jQuery.
const buttons = document.querySelectorAll('.button');
const hiddens = document.querySelectorAll('.hidden');
buttons.forEach((btn) => {
btn.addEventListener('click', btnClicked)
function btnClicked(e) {
hiddens.forEach((hidden) => {
if(e.target.dataset.btn == hidden.dataset.content) {
hidden.classList.toggle('height')
} else {
hidden.classList.remove('height')
}
})
}
})
.hidden {
background: #ccc;
margin-top: 2%;
padding-left:2%;
overflow: hidden;
transition: height 200ms;
height: 0; /* <-- set this */
}
.hidden.height {
height: 50px;
}
.button {
padding: 10px;
color: white;
background-color: #2da6b5;
border: none;
margin-top: 5px;
width:90%;
margin-left: 5%;
cursor: pointer;
}
.button:hover {
filter: brightness(.9);
}
#row {
display: flex;
}
.column {
flex: 50%;
}
<div id="row">
<div class="column">
<button class="button" data-btn="one">I am Button #1</button>
<button class="button" data-btn="three">I am Button #3</button>
</div>
<div class="column">
<button class="button" data-btn="two">I am Button #2</button>
<button class="button" data-btn="four">I am Button #4</button>
</div>
</div>
<div class="hidden" data-content="one">
<p class="content"> So here I am #1</p>
</div>
<div class="hidden" data-content="two">
<p class="content"> So here I am #2</p>
</div>
<div class="hidden" data-content="three">
<p class="content"> So here I am #3</p>
</div>
<div class="hidden" data-content="four">
<p class="content"> So here I am #4</p>
</div>
Also, please do not use the same ID at multiple elements.

I have 3 Div, how to select 2 div with a click (one by one) and to display none (or other) the third one in Javascript

i have 3 div (class) in my html and i want with a "addEventListener click" hide the third div when two div has been clicked. Then i have the two cliked div in sort of visibility mod "on" and the one not clicked visibility mod "off"
My actual html structure code :
<div class="card" id="card01">
</div>
<div class="card" id="card02">
</div>
<div class="card" id="card03">
</div>
And my JS:
let pokemons = document.getElementsByClassName("card");
//console.log(pokemons.length);
for(let i = 0 ; i < (pokemons.length) ; i++){
pokemons[i].addEventListener('click',function(){
});
}
You can achieve this by adding a "clicked" class to each div that is clicked, and then checking to see if 2 divs have been clicked. Then you can hide the div which has not been clicked by selecting the divs that don't have the "clicked" class.
pokemons[i].addEventListener("click", function(event) {
event.target.classList.add("clicked");
let clicked = document.getElementsByClassName("clicked");
if (clicked.length === 2) {
document.querySelector(".card:not(.clicked)").hidden = true;
}
});
let pokemons = document.getElementsByClassName("card");
for (let i = 0; i < (pokemons.length); i++) {
pokemons[i].addEventListener("click", function(event) {
event.target.classList.add("clicked");
let clicked = document.getElementsByClassName("clicked");
if (clicked.length === 2) {
document.querySelector(".card:not(.clicked)").hidden = true;
}
});
}
.card {
background-color: gold;
height: 10em;
width: 7em;
margin: 1em;
float: left;
padding: 1em;
}
.card::after {
content: attr(id);
}
<div class="card" id="card01">
</div>
<div class="card" id="card02">
</div>
<div class="card" id="card03">
</div>

How to add eventlistener to dynamically created divs

How to add event delegation to dynamically created divs, to change property of the target div? I've tried several suggestions that I found for event delegation but none of them work. I think I'm making some mistakes but I don't know how to fix.
I am trying to develop a file thumbnail list interface with HTML and JavaScript. I made a method that draws thumbnails dynamically from an Array. And now I want to add some functions to manipulate the thumbnails, ex. changing border color of the item(div) when it is clicked.
First I tried loop-method to add event listeners to the divs, but it didn't work well. And now I learned that event delegation is better way to add event listeners to dynamically created elements. But the problem is that though I'v tried codes but they didn't work at all.
I think I am making some mistakes or mis-using methods but I don't know what is the problem.
JavaScript
function drawThumbnails(area, list){
var j
var createdList = []
for (j=0; j<list.length; j++){
var thmb = document.getElementById("fileThumb");
var name = document.getElementById("itemName");
var date = document.getElementById("itemDate");
var thmbimg = document.getElementById("fileThumbImage");
var thmbicon = document.getElementById("file_icon_thumb");
name.innerHTML=list[j][0];
date.innerHTML=list[j][1];
if (list[j][2] == "folder"){
thmbimg.src = "thmb_folder.png";
thmbicon.style.display = "none";
}
else {
if (list[j][2] == "img"){
thmbimg.src=getthmbimgsample();
}
else{
thmbimg.src = getThmbimg(list[j][2]);
}
thmbicon.style.display = "block";
thmbicon.src = getThmbicon(list[j][2]);
}
var cln = thmb.cloneNode(true);
cln.style.display = "block";
document.getElementById(area).append(cln);
createdList.push(cln);
}
thmbLists.push(createdList);
}
drawThumbnails("folderArea", folders);
drawThumbnails("fileArea", files);
document.getElementById("folderArea").addEventListener('click',function(e){
if(e.target && e.target.className == "fileThumb"){
e.target.style.borderColor = "#408CFF";
}
});
HTML
<body>
<div class = "contentArea" id="contentArea">
<div class = "thumbArea" id="folderArea">
<div class = "fileThumb" id="fileThumb">
<img src="icon_thumb_folder.png" class="fileThumb_normal" id="fileThumbImage">
<div class="fileName">
<img src="icon_thumb_file.png" style="width: 20px;" id="file_icon_thumb">
<div class="fileNameLine" id = "itemName">File/FolderName</div>
<div class="fileNameDate" id="itemDate">Date</div>
</div>
</div>
</div>
<div class = "contentAreaSectionHeader">
<input type="checkbox" id="chTest2" name="chTest2">
<label for="chTest2"><span>Files</span></label>
</div>
<div class = "thumbArea" id="fileArea">
</div>
</body>
CSS
.fileThumb{
width: 213px;
height: 183px;
border-radius: 2px;
border-style: solid;
border-width: 1px;
border-color: #EEEEEE;
text-align: center;
position: relative;
float:left;
margin: 18px;
display: none;
overflow: hidden;
}

My next and prev button for the list isn't working

The problem: I am not able to get the value of the HTML list from javascript. Each time user click next button, the program will count how many times the user clicks the next button. In javascript, I called the HTML list and iterate it. inside for loop, I called user click on next button number and add 1, The result of the sum will go inside the array and display that array line data. I don't know because of some reason I can't able to get data. Let me know if you get confused
Here is the HTML code
<div id="Border" class="">
<div id="Topic_List" class="creature">
<ul id="ListName" class="">
<li> Google </li>
<li>Facebook</li>
<li> Google </li>
</ul>
</div>
</div>
<div id="" class="" style="clear:both;"></div>
<div id="InputInsideFullCover" class="">
<textarea id="File_Name" name="File_Name"></textarea>
</div>
<button id="clickme" onclick="Next()"> Next </button>
<button onclick="Prev()"> Prev </button>
Here is the JavaScript code
<script>
function Next(){
var button = document.getElementById("clickme"),
count = 0;
button.onclick = function() {
count += 1;
var ul = document.getElementById("ListName");
var items = ul.getElementsByTagName("li");
for (var i = 0; i < items.length; ++i) {
var GetButtonClickValue = count;
var AddOne = GetButtonClickValue + 1;
var file_name = document.getElementById("ListName").innnerHTML=items[AddOne];
document.getElementById("File_Name").href = file_name;
var url_to_file = "http://www.example.com/"+file_name;
$.ajax({
url: url_to_file,
type:'HEAD',
error: function()
{
alert('data not found.');
},
success: function()
{
}
});
}
if(count > 9){
count = " ";
count = 1;
button.innerHTML = "Click me: " + count;
}
};
}
</script>
here is the CSS code
<style>
#Border{margin:5px auto;padding:0;width:50px;height:auto;border:1px solid #666;background-color:#f1f1f1}
#InputInsideFullCover{margin:5px;padding:0;width:700px;height:auto;}
#File_Name{margin:0;padding:0;width:638px;height:25px;resize:none;}
#Topic_List{margin:5px;padding:0;width:640px;height:auto;}
#Topic_List ul{margin:0px;padding:0;height:auto;width:12px;}
#Topic_List li{margin:0px;padding:0;list-style-type:none;float:left}
#button{
background-color: #4CAF50; /* Green background */
border: 1px solid green; /* Green border */
color: white; /* White text */
padding: 10px 24px; /* Some padding */
cursor: pointer; /* Pointer/hand icon */
width: 50%; /* Set a width if needed */
display: block; /* Make the buttons appear below each other */
}
.btn-group button:not(:last-child) {
border-bottom: none; /* Prevent double borders */
}
/* Add a background color on hover */
.btn-group button:hover {
background-color: #3e8e41;
}
</style>
You are declaring count to 0 at the beginning of the function. So every time the button is clicked count equals 0 and then one is added. (It will always be 1) You need to pull the count var outside of the function. This will also be useful for your Prev function. I bet that your Next and prev functions will be similar enough to make only one function. Call your function with true or false to add or subtract the count.
Just Add this
<script src="jquery-3.4.0.min.js"></script>
in your head tag before the external script tag
beacuse you are using ajax you need jquery

Press a button and change the color of box elsewhere on page [duplicate]

This question already has answers here:
How to change div background color on button click?
(2 answers)
Closed 3 years ago.
I'm very new to coding and have learned my very limited knowledge from forums and tutorials online. I seem to be up against a problem that I cannot for the life of me figure out.
My goal is to press one of three buttons (Leadership, Program, Team) at the top of a grid (the grid lists our services) and have the appropriate grid box change colors. For example, pressing the Leadership button would turn a grid box blue, Program would turn a grid box yellow, and Team would turn a grid box green. This means that a grid box might be linked to more than one of the buttons, as our services overlap. So depending on what button is pressed, a single grid box might change to blue, yellow, or green.
I figured out how to do toggle buttons which show the body onclick. BUT that means A LOT of redundancy. (I would have to do a grid with the appropriately colored boxes for Leadership, another one for Program, and another one for Team). So, I think I'm on the wrong path there.
I've searched toggles, buttons, anchors, event listeners, targets, you name it. It seems like it all relates to the button itself, not how the button relates to an element on the page.
I am very grateful to anyone who can point me in the right direction! Thank you!
function goToAnchor(anchor) {
var loc = document.location.toString().split('#')[0];
document.location = loc + '#' + anchor;
return false;
}
var divs = ["Div1", "Div2", "Div3", "Div4"];
var visibleDivId = null;
function divVisibility(divId) {
if(visibleDivId === divId) {
visibleDivId = null;
} else {
visibleDivId = divId;
}
hideNonVisibleDivs();
}
function hideNonVisibleDivs() {
var i, divId, div;
for(i = 0; i < divs.length; i++) {
divId = divs[i];
div = document.getElementById(divId);
if(visibleDivId === divId) {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
}
.square-grey {
display: table-cell;
height: 100px;
width: 600px;
text-align: center;
vertical-align: middle;
border-radius: 5%;
/*make it pretty*/
background: #F5F5F5;
color: #999999;
padding: 10px 15px 10px 15px;
font: 20px "helvetica";
font-weight: 350;
box-shadow: 2px 3px 3px #999999;
}
div.highlit {
padding: 25px;
}
<div class="row">
<div class="buttons">
<div style="text-align:center">
<div class="col-sm-4">
Enterprise
</div>
<div class="col-sm-4">
Program
</div>
<div class="col-sm-4">
Team
</div>
</div>
</div>
</div>
<div class="inner_div">
<div id="Div1">
<div class="row">
<div style="text-align:center">
<div class="col-sm-3">
<div class="top-buffer">
<div class="square-grey">
Strategic Alignment
</div>
</div>
</div>
<div class="col-sm-3">
<div class="top-buffer">
<div class="square-grey">
Adaptive Leadership
</div>
</div>
</div>
<div class="col-sm-3">
<div class="top-buffer">
<div class="square-grey">
Portfolio Management
</div>
</div>
</div>
<div class="col-sm-3">
<div class="top-buffer">
<div class="square-grey">
Cultural Shift
</div>
</div>
</div>
</div>
</div>
</div>
<div id="Div2" style="display: none;">I'm Div Two</div>
<div id="Div3" style="display: none;">I'm Div Three</div>
</div>
</div>
Edited answer, you can add IDs to the boxes and pass them to function.
const changeColor = (elements, color) => {
elements.forEach(el => {
const element = document.querySelector(el);
element.style.backgroundColor = color;
})
}
.colorbox {
width: 100px;
height: 100px;
background-color: aquamarine;
margin-bottom: 10px;
}
<div class="colorbox" id="colorbox1"></div>
<div class="colorbox" id="colorbox2"></div>
<div class="colorbox" id="colorbox3"></div>
<button onclick="changeColor(['#colorbox1', '#colorbox3'], 'tomato')">Change 1 & 3 to tomato</button>
<button onclick="changeColor(['#colorbox1', '#colorbox2'], 'aliceblue')">Change 1 & 2 to aliceblue</button>
<button onclick="changeColor(['#colorbox2', '#colorbox3'], '#ff0000')">Change 2 & 3 to reddest</button>

Categories