I hava a page that uses tabulator to make a table. On each row of the table I habe a small thumbnail. When I click on the thumbnail a gallery opens. I want to classify the image by clicking some buttons (yes, no etc). When I click on one buttons I want to close the gallery and then have javascript go to the next cell gallery: trigger a click on the next row's cell. I can get the cell but I cannot manage to trigger the cell click form the javascript portion. I have tried (on the cell I want to use):
//inside btn-clicked function
//after closing the gallery just want to trigger default tabulator cellClick event!
cellEl = cell.getElement();
$(cellEl).trigger('click')
and
$("document").trigger('cellClick', cell)
$("#main-table").trigger('cellClick', [cell])
None of these work.
Here is a JSFiddle: https://jsfiddle.net/q5fuon6z/
This is a totally artificial example but this demonstrates a cycle of the children when clicked.
$("#main-table").on('click', '.cell-mate', function(event) {
let cells = $('.cell-mate');
cells.toggleClass("occupied next-up", false);
$(this).toggleClass("occupied");
let myIndex = $(this).index();
let clickNext = $(this).index() == cells.last().index() ? cells.first() : $(this).next('.cell-mate');
clickNext.trigger('cellClick', [$(this), myIndex, clickNext]);
});
$('.cell-mate').on('cellClick', function(event, cell, prevIndex, nextUp) {
nextUp.toggleClass('next-up');
$('#monitor').html(cell.html() + " at " + prevIndex + " nudged " + nextUp.html() +
" at " + nextUp.index());
});
//start it all off (or comment out to start with a user action)
$("#main-table").find('.cell-mate').eq(0).trigger('click');
.occupied {
border: solid 1px #0000ff;
}
#monitor {
border: dashed 2px #ddffdd;
margin: 1em;
}
.next-up {
background-color: #ffdddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main-table">
<div class="cell-mate">bunk Able</div>
<div class="cell-mate">bunk Bravo</div>
<div class="cell-mate">bunk Cat</div>
<div class="cell-mate">bunk Dog</div>
<div class="cell-mate">bunk Elephant</div>
<div class="cell-mate">bunk Giraffe</div>
</div>
<div id="monitor"></div>
Here is another example with targets specified as "next". With this example, it does not matter what order they are in since they specify a target; which I assume exists and did not account for any missing.
$("#main-table").on('click', '.cell-mate', function(event) {
let cells = $('.cell-mate');
cells.toggleClass("occupied next-up", false);
$(this).toggleClass("occupied");
let mytarget = $(this).data("nextup");
let nextOne = cells.filter(function() {
return $(this).data("iam") == mytarget;
});
let clickNext = $(this).index() == cells.last().index() ? cells.first() : $(this).next('.cell-mate');
nextOne.trigger('cellClick', [$(this), $(this).index()]);
});
$('.cell-mate').on('cellClick', function(event, cell, prevIndex) {
$(this).toggleClass('next-up');
$('#monitor').html(cell.html() + " at " + prevIndex + " nudged " + $(this).html());
});
//start it all off (or comment out to start with a user action)
$("#main-table").find('.cell-mate').eq(0).trigger('click');
.occupied {
border: solid 1px #0000ff;
}
#monitor {
border: dashed 2px #ddffdd;
margin: 1em;
}
.next-up {
background-color: #ffdddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main-table">
<div class="cell-mate" data-iam="able" data-nextup="beans">bunk Able</div>
<div class="cell-mate" data-iam="g" data-nextup="able">bunk Giraffe</div>
<div class="cell-mate" data-iam="beans" data-nextup="dog">bunk Bravo</div>
<div class="cell-mate" data-iam="cat" data-nextup="elephant">bunk Cat</div>
<div class="cell-mate" data-iam="dog" data-nextup="cat">bunk Dog</div>
<div class="cell-mate" data-iam="elephant" data-nextup="g">bunk Elephant</div>
</div>
<div id="monitor"></div>
Apparently the correct syntax for tabulator is:
$(cell.getElement()).trigger('click')
Related
<div class="heading">
<div id="link"><a>My Name</a></div>
<div class="pro">My Career</div>
</div>
I tried to search for an answer but am just getting how to only change the background or with a button.
Find the link element.
Add a click listener to it.
On click of the link element, generate a random color and update the element's color style attribute.
Here is the demo-
// find the link element
let linkEl = document.querySelector('#link a');
// attach a click listener to it
linkEl.addEventListener('click', () => {
// Generate a random color
let color = '#' + Math.floor(Math.random() * 16777215).toString(16);
// set color to the link element
linkEl.style.color = color;
})
a {
cursor: pointer;
}
<div class="heading">
<div id="link">
<a>My Name (click me to change my color)</a>
</div>
<div class="pro">My Career</div>
</div>
Yea probably
<script>
function changeLinkColor() {
// Generate a random color in the format '#RRGGBB'
let randomColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
// Get the link element
let link = document.querySelector("#link a");
// Set the link color to the random color
link.style.color = randomColor;
}
</script>
You can try this in any case:
function generateColor(){
return Math.floor(Math.random() * 255);
}
document.querySelectorAll('.anchor').forEach(el => {
el.onclick = function(e){e.target.style.backgroundColor = 'rgb('+ generateColor() + ',' + generateColor() + ','+ generateColor() + ')';
}
});
.anchor{
display: inline-block;
background:dodgerblue;
text-decoration: none;
color:#fff;
border-radius: 10px;
text-shadow: 0 0 2px #000;
padding: 10px;
margin:10px
}
<a class="anchor anchor1" href="#">click 1</a>
<div class="anchor anchor2" href="#">click 1</div>
<p class="anchor anchor3" href="#">click 1</p>
Please check this solution and let me know if its help you in any way.
I have a few buttons across a site I am building, certain buttons have one class while others have another. What I am trying to do is find the best way to find the clicked button without having an event listener for each individual button. I have come up with the below 2 for loops to find all the buttons with class button-1 and class button-2. Being fairly new to javascript i just don't want to get into bad habits so would appreciate any advice on the best way to achieve this.
<section>
<div class="button--1"></div>
<div class="button--1"></div>
<div class="button--2"></div>
</section>
<section>
<div class="button--2"></div>
<div class="button--1"></div>
<div class="button--2"></div>
</section>
var button1 = document.querySelectorAll('.button--1');
var button2 = document.querySelectorAll('.button--2');
for (var a = 0; a < button1.length; a++) {
button1[a].addEventListener('click',function(){
//do something
});
}
for (var b = 0; b < button2.length; b++) {
button1[b].addEventListener('click',function(){
//do something
});
}
If you plan to have multiple other classes like button--3, …4 … …15,
You must want to target all div elements which class starts (^=) with "button":
(Note that you can do it in the CSS too!)
var allButtons = document.querySelectorAll('div[class^=button]');
console.log("Found", allButtons.length, "div which class starts with “button”.");
for (var i = 0; i < allButtons.length; i++) {
allButtons[i].addEventListener('click', function() {
console.clear();
console.log("You clicked:", this.innerHTML);
});
}
/* Some styling */
section {
margin: 8px 0;
border: 1px solid gray;
}
section div {
border: 1px solid lightgray;
display: inline-block;
margin-left: 8px;
padding: 4px 8px;
width: 30px;
}
section div[class^=button] {
background: lightgray;
cursor: pointer;
}
<span>You can click on the buttons:</span>
<section>
<div class="button--1">s1-1</div>
<div class="button--2">s1-2</div>
<div class="button--3">s1-3</div>
<div class="button--4">s1-4</div>
</section>
<section>
<div class="button--1">s2-1</div>
<div class="button--2">s2-2</div>
<div class="button--3">s2-3</div>
<div class="button--4">s2-4</div>
</section>
<section>
<div class="not-a-button">not1</div>
<div class="not-a-button">not2</div>
<div class="not-a-button">not3</div>
<div class="not-a-button">not4</div>
</section>
Hope it helps.
Try using event delegation
(function() {
document.body.addEventListener("click", clickButtons);
// ^ one handler for all clicks
function clickButtons(evt) {
const from = evt.target;
console.clear();
if (!from.className || !/button--\d/i.test(from.className)) { return; }
// ^check if the element clicked is one of the elements you want to handle
// if it's not one of the 'buttons', do nothing
console.log("you clicked " + from.classList);
}
}())
.button--1:before,
.button--2:before {
content: 'BTTN['attr(class)']';
}
.button--1,
.button--2 {
border: 1px solid #999;
background: #eee;
width: 220px;
padding: 3px;
text-align: center;
}
<section>
<div class="b1 button--1 section1"></div>
<div class="b2 button--1 section1"></div>
<div class="b3 button--2 section1"></div>
</section>
<section>
<div class="b4 button--2 section2"></div>
<div class="b5 button--1 section2"></div>
<div class="b6 button--2 section2"></div>
</section>
You can use multiple selectors in the string of querySelctorAll() by separating them with a ,
var button1 = document.querySelectorAll('.button--1');
var button2 = document.querySelectorAll('.button--2');
var allButtons = document.querySelectorAll('.button--1, .button--2');
console.log(button1.length);
console.log(button2.length);
console.log(allButtons.length);
<section>
<div class="button--1"></div>
<div class="button--1"></div>
<div class="button--2"></div>
</section>
<section>
<div class="button--2"></div>
<div class="button--1"></div>
<div class="button--2"></div>
</section>
My suggestion is to use jQuery so that you can do it something like this:
$(document).on('click', '.button--1', function() {
// Do something
});
$(document).on('click', '.button--1', function() {
// Do something
})
But a clean approach for pure Javascript is to create a function that binds a callback for the event.
function bindEvent(callback, eventType, targets) {
targets.forEach(function(target) {
target.addEventListener(eventType, callback);
});
};
var button1 = document.querySelectorAll('.button--1');
var button2 = document.querySelectorAll('.button--2');
bindEvent(function() {
// do something
}, 'click', button1);
bindEvent(function() {
// do something
}, 'click', button2);
The click event is fired when a pointing device button (usually a mouse's primary button) is pressed and released on a single element.
This documentation will help you to understand how it works MDN - Click event
I have two parent divs: .inputs and .infoBoxes. Each of them have an equal number of children. When the user clicks into the first .input in .inputs, the first .infoBox in .infoBoxes should slideDown(). Same for second, third, etc. I'd like to do this without re-writing the same code for each pair. So far I have:
var $inputs = $('.inputs').children();
var $infoBoxes = $('.infoBoxes').children();
for(var i = 0; i < $inputs.length; i++ ) {
$($inputs[i]).find('.input').focus(function() {
$($infoBoxes[i]).slideDown();
})
$($inputs[i]).find('.input').blur(function() {
$($infoBoxes[i]).slideUp();
})
}
This isn't working but I have tried replacing i with the indexes of each div.
$($inputs[0]).find('.input').focus(function() {
$($infoBoxes[0]).slideDown();
})
$($inputs[0]).find('.input').blur(function() {
$($infoBoxes[0]).slideUp();
})
repeat...
repeat...
repeat...
This works but isn't very DRY. I'm looking for a better solution that won't have me repeating a bunch of code.
First code will not work, because you using same variable for all internal functions. You should wrap it into function, which will create local variable for index. Try following code:
var $inputs = $('.inputs').children();
var $infoBoxes = $('.infoBoxes').children();
for(var i = 0; i < $inputs.length; i++ ) {
(function(ix) {
$($inputs[ix]).find('.input').focus(function() {
$($infoBoxes[ix]).slideDown();
})
$($inputs[ix]).find('.input').blur(function() {
$($infoBoxes[ix]).slideUp();
})
})(i);
}
slideDown is used for showing elements. I am guessing you want to hide elements, since you are clicking on them and you cant click an hidden element. Use hide or slideUp to hide elements.
$(".input, .infobox").on("click", function() {
var ind = $(this).index();
$(".infobox:eq(" + ind + "), .input:eq(" + ind + ")").hide(500);
});
.input,
.infobox {
widht: 100%;
height: 50px;
text-align: center;
margin: 5px 0;
color: white;
}
.input {
background: red;
}
.infobox {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inputs">
<div class="input">1</div>
<div class="input">2</div>
<div class="input">3</div>
<div class="input">4</div>
<div class="input">5</div>
</div>
<div class="infoboxes">
<div class="infobox">1</div>
<div class="infobox">2</div>
<div class="infobox">3</div>
<div class="infobox">4</div>
<div class="infobox">5</div>
</div>
Have a problem and can't get to solve it. Tried to use QuerySelectorAll and comma separating with GetElementsByClassName, but that didn't work, so I am wondering how to solve this problem.
I have this HTML:
<div class="area">Test title
<div class="some content" style="display: none">blablbala
<input></input>
</div>
<div class="two">This should be clickable too</div>
</div>
<div class="area">
Test title
<div class="some content">
blablbala
<input></input>
</div>
<div class="two">This should be clickable too</div>
</div>
JS:
function areaCollapse() {
var next = this.querySelector(".content");
if (this.classList.contains("open")) {
next.style.display = "none";
this.classList.remove("open");
} else {
next.style.display = "block";
this.classList.add("open");
}
}
var classname = document.getElementsByClassName("area");
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', areaCollapse, true);
}
http://jsfiddle.net/1BJK903/nb1ao39k/6/
CSS:
.two {
position: absolute;
top: 0;
}
So now, the div with classname "area" is clickable. I positioned the div with class "two" absolute and now the whole div is clickable, except where this other div is. If you click on the div with classname "two", it doesn't work (it does not collapse or open the contents). How can I make this work, without changing the structure?
One way is using a global handler, where you can handle more than one item by checking its id or class or some other property or attribute.
Below snippet finds the "area" div and pass it as a param to the areaCollapse function. It also check so it is only the two or the area div (colored lime/yellow) that was clicked before calling the areaCollapse.
Also the original code didn't have the "open" class already added to it (the second div group), which mean one need to click twice, so I change the areaCollapse function to check for the display property instead.
function areaCollapse(elem) {
var next = elem.querySelector(".content");
if (next.style.display != "none") {
next.style.display = "none";
} else {
next.style.display = "block";
}
}
window.addEventListener('click', function(e) {
//temp alert to check which element were clicked
//alert(e.target.className);
if (hasClass(e.target,"area")) {
areaCollapse(e.target);
} else {
//delete next line if all children are clickable
if (hasClass(e.target,"two")) {
var el = e.target;
while ((el = el.parentElement) && !hasClass(el,"area"));
if (targetInParent(e.target,el)) {
areaCollapse(el);
}
//delete next line if all children are clickable
}
}
});
function hasClass(elm,cln) {
return (" " + elm.className + " " ).indexOf( " "+cln+" " ) > -1;
}
function targetInParent(trg,pnt) {
return (trg === pnt) ? false : pnt.contains(trg);
}
.area {
background-color: lime;
}
.two {
background-color: yellow;
}
.area:hover, .two:hover {
background-color: green;
}
.some {
background-color: white;
}
.some:hover {
background-color: white;
}
<div class="area">Test title clickable 1
<div class="some content" style="display: none">blablbala NOT clickable 1
</div>
<div class="two">This should be clickable too 1</div>
</div>
<div class="area">Test title clickable 2
<div class="some content">blablbala NOT clickable 2
</div>
<div class="two">This should be clickable too 2</div>
</div>
<div class="other">This should NOT be clickable</div>
You need to find your two elements while you're binding classname, and bind that as well.
var classname = document.getElementsByClassName("area");
for(var i=0; i < classname.length; i++){
classname[i].addEventListener('click', areaCollapse, true);
var twoEl = classname[i].getElementsByClassName("two")[0];
twoEl.addEventListener('click', function(e) { console.log('two clicked'); });
}
If you want to use jQuery:
$('.two').click(function(){
//action here
});
I have item group list
<div id="MainMenu">
<div class="list-group panel">
Menu 1
<div class="collapse" id="why">
Menu 1 a
Menu 1 b
Menu 1 c
Menu 1 d
Menu 1 e
Menu 1 f
</div>
Menu 2
<div class="collapse" id="joinus">
Menu 2 a
Menu 2 b
Menu 2 c
Menu 2 d
Menu 2 e
</div>
</div>
</div>
I want to change background of active list item, I Know how to change background, but I am unable to get which list is active, or inactive by JavaScript, tried lots of solution given on others but didn't woJrk.
JsFiddle
UPDATE:
Don't know why bootstrap isn't doing it, but here's some jQuery on a fiddle for you. The alert is displaying the href that is active.
Is that what you're after?
Update - 09/01/2022
Edited the old fiddle, here's the new one http://jsfiddle.net/dh7t3cbp/1/
$('.list-group').on('click', '> a', function(e) {
var $this = $(this);
$('.list-group').find('.active').removeClass('active');
$this.addClass('active');
alert($this.attr('href') + ' is active');
});
$('.list-group .collapse').on('click', '> a', function(e) {
var $this = $(this),
$parent = $this.parent('.collapse');
$parent.find('.active').removeClass('active');
$this.addClass('active');
alert($this.attr('href') + ' is active');
});
.list-group panel.active, .list-group panel.active a.active {
background-color: #030;
border-color: #aed248;
}
Add the following css in your code as :
.list-group-item[aria-expanded="true"]{
background-color: black !important;
border-color: #aed248;
}
Demo
What i does it assign and id to every link in list that is also the page name, and made a js function that is called on body load of the page. the function get the current file name from url and determines which page is this, then by js i made that link class active. this solve my problem. however i share this solution for others to improvement.
function get_current_page() {
var pathArray = window.location.pathname.split("/");
var current_page = pathArray[pathArray.length - 1];
current_page_array = current_page.split(".");
current_page = current_page_array[0];
if (
current_page == "students" ||
current_page == "my-profile" ||
current_page == "faqs" ||
current_page == "forecast-career"
) {
document.getElementById("joinuslist").className += " active";
document.getElementById("joinus").className += " in";
if (current_page == "students") {
document.getElementById("students").className += " active";
} else if (current_page == "faqs") {
document.getElementById("faqs").className += " active";
} else if (current_page == "forecast-career") {
document.getElementById("forecast-career").className += " active";
} else if (current_page == "my-profile") {
document.getElementById("my-profile").className += " active";
} else {
}
} else if (
current_page == "values" ||
current_page == "ambassadors" ||
current_page == "documentary"
) {
if (current_page == "values") {
document.getElementById("values").className += " active";
} else if (current_page == "ambassadors") {
document.getElementById("ambassadors").className += " active";
} else if (current_page == "documentary") {
document.getElementById("documentary").className += " active";
} else {
}
}
}
.list-group-item.active:hover {
background-color: #aed248 !important;
border-color: #aed248 !important;
}
.list-group-item.active,
.list-group-item.active:hover {
background-color: #007715 !important;
border-color: #aed248 !important;
}
#joinus .list-group-item.active,
.list-group-item.active:hover {
background-color: #adce1b !important;
border-color: #adce1b !important;
}
#whyptcl .list-group-item.active,
.list-group-item.active:hover {
background-color: #adce1b !important;
border-color: #adce1b !important;
}
.panel {
margin-bottom: 20px;
background-color: transparent !important;
border: 0px solid transparent;
border-radius: 5px;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
}
<body onload="get_current_page()">
<div id="MainMenu">
<div class="list-group panel">
<a
id="whylist"
href="#why"
class="list-group-item"
data-toggle="collapse"
data-parent="#MainMenu"
>Menu 1</a
>
<div class="collapse" id="why">
<a
id="values"
href="values.html"
onclick="activate(this)"
class="list-group-item"
data-toggle="collapse"
data-parent="#SubMenu1"
>Menu 1 a</a
>
<a
id="ambassadors"
href="ambassadors.html"
onclick="activate(this)"
class="list-group-item"
>Menu 1 b</a
>
<a
id="documentary"
href="documentary.html"
onclick="activate(this)"
class="list-group-item"
>Menu 1 c</a
>
</div>
<a
id="joinuslist"
href="#joinus"
class="list-group-item"
data-toggle="collapse"
data-parent="#MainMenu"
>Menu 2</a
>
<div class="collapse" id="joinus">
<a
id="my-profile"
href="my-profile.html"
onclick="activate(this)"
class="list-group-item"
>Menu 2 a</a
>
<a
id="students"
href="students.html"
onclick="activate(this)"
class="list-group-item"
>Menu 2 b</a
>
<a
id="forecast-career"
href="forecast-career.html"
onclick="activate(this)"
class="list-group-item"
>Menu 2 c</a
>
<a
id="faqs"
href="faqs.html"
onclick="activate(this)"
class="list-group-item"
>Menu 2 e</a
>
</div>
</div>
</div>
</body>
The solution is simple but maybe not obvious.
You can pass this (the clicked element) to an onclick event handler and then set the active class on the selected menu.
var activate = function(el) {
var current = document.querySelector('.active');
if (current) {
current.classList.remove('active');
}
el.classList.add('active');
}
I created this Fiddle to answer your question
http://jsfiddle.net/Ltp9qLox/9/
The script can be greatly improved, this is just an example. I'm not aware of any non-JS way to achieve the same result.
You can also store the old activated element so you don't have to use query selector every time, in this way the script would be
var current;
var activate = function(el) {
if (current) {
current.classList.remove('active');
}
current = el;
el.classList.add('active');
}
Bu then you have to initialize currentwith the value of the starting element.
Adding Persistency
Of course any change to the style of an element can't survive after a refresh without implementing some kind of persistency that is something completely different than the simple implementation. Keep in mind that there are hundreds of different ways to achieve this, one of which is NOT refreshing at all the page.
Anyway if you prefer the quick and dirt way then using localStorage is probably the best solution. This is a simple implementation
var currentHref = localStorage.getItem("currentSelected");
var current = currentHref ? document.querySelector('[href="'+currentHref+'"]') : null;
function activate(el) {
if (current && current !== el) {
current.classList.remove('active');
}
current = el;
current.classList.add('active');
localStorage.setItem("currentSelected", current.getAttribute('href'));
}
Basically you save something that you can use to recognize the element that was selected, in this case i used the href attribute value because in our case that is unique, but you could also assign id or other attributes to the elements and use that.
Then on load i read the localStorage to retrieve the saved href and if found i get the element inside the page using a simple querySelector.
Just remember that copy-pasting this kind of solution doesnt help you building better websites, you should read articles on the internet and implement what solution is best for your own use case.
Just to change the active item background color, (I've changed to grey from default - blue) add this to your css:
.list-group-item.active {
background-color: grey;
border-color: grey; }
You can add these Bootstrap classes;
.list-group-item-dark
.list-group-item-success
.list-group-item-warning
.list-group-item-primary
.list-group-item-danger
.list-group-item-secondary
.list-group-item-info