Since .foreach and .map won't work on a nodelist, is the only way to work with the elements in a nodelist through a for loop?
What I'm trying to accomplish is adding different event listeners to the different elements within a nodelist. If the element has the class name of "bold", then the iBold() function should be run, and likewise for "italics" and "underline". Having multiple for loops running to handle each individually feels excessive, so that's why I'm trying to work with one loop to handle all rich text. However, if there's a better way to go about this, I'd really like to know since it seems as though I'm just over-thinking all of this.
var QSA = document.querySelectorAll('div > form > div > a.richText');
for (var rtIndex = 0; rtIndex < QSA.length;rtIndex++) { //Rich text event listeners
var rtid = QSA[rtIndex].id;
var targetiFrame = document.getElementById(rtid).getAttribute('data-pstid');
if (document.getElementById(rtid).className == "richText bold") { //Bold text event listener
QSA[rtIndex].addEventListener('click', function() {
if (targetiFrame != 0) {iBold(targetiFrame);}
else {
document.getElementById('richTextField').contentDocument.execCommand('bold', false, null);
document.getElementById('richTextField').contentWindow.focus();
}
}, false);
} else if (document.getElementsByClassName('richText')[rtIndex].className == 'richText underline') { //Underline text event listener
document.getElementsByClassName('richText')[rtIndex].addEventListener('click', function() {
if (targetiFrame == 0) {
document.getElementById('richTextField').contentDocument.execCommand('underline', false, null);
document.getElementById('richTextField').contentWindow.focus();
} else {iUnderline(targetiFrame);}
}, false);
} else if (document.getElementsByClassName('richText')[rtIndex].className == 'richText italic') { //Italic text event listener
document.getElementsByClassName('richText')[rtIndex].addEventListener('click', function() {
if (targetiFrame == 0) {
document.getElementById('richTextField').contentDocument.execCommand('italic', false, null);
document.getElementById('richTextField').contentWindow.focus();
} else {iItalic(targetiFrame);}
}, false);
}
}
for (var sbmtIndex = 0;sbmtIndex < document.getElementsByClassName('sbmtPost').length;sbmtIndex++) { //Event listener for submitting posts or comments
var iSubmt = document.querySelectorAll('form > div')[sbmtIndex];
document.querySelectorAll('form > div > .sbmtPost')[sbmtIndex].addEventListener('click', function() {
var pstData = iSubmt.querySelector('form > div > .sbmtPost').getAttribute('data-cmtid');
var cPrntID = iSubmt.querySelector('form > div > .sbmtPost').getAttribute('data-pstid');
sendData(pstData, cPrntID); //Post Data (data being the id) and Comment Parent Id. Comments are posts. Variables only used for comments
}, false);
}
If you don't mind converting your NodeList to an Array, you can use:
var nodeArray = Array.prototype.slice.call(nodeList);
Then you can use all the functional methods on the resulting Array.
Note: this is not cross-browser compatible, but neither is .forEach, so I don't think it's an issue.
<div class="btn" data='btn1'>btn1</div>
<div class="btn" data='btn2'>btn2</div>
<div class="btn" data='btn3'>btn3</div>
const btns = document.getElementsByClassName('btn');
function getBtns(el, callback) {
Array.prototype.forEach.call(el, function(node) {
// Wrap below in if() condition here.
node.addEventListener('click', callback);
});
}
getBtns(btns, function() {
console.log(this.getAttribute('data'));
});
this points to the button that's clicked.
Related
I have a list of ids, when one of them is clicked I want to give it the attribute .className="open.
So far what I've done is to put all ids in a list and try to loop through them.
const memberB = document.querySelectorAll('#memberA, #memberAA, #memberAAA ');
for (var i = 0; i < memberB.length; i++) {
memberB[i].onclick = function(){
alert(memberB[i])
if(memberB[i].className=="open"){
memberB[i].className="";
}
else{
memberB[i].className="open";
}
}
What did I do wrong, I try to alert to see if I get the element that i clicked, all i get is 'undefined'.
you can use forEach to loop the NodeList which use querySelectorAll method, and use addEventListener to watch click event happen on all the elements you selected. Finally, use Element.classList.toggle method to toggle the class open or close
there is an example of toggle its background color after click
const members = document.querySelectorAll('.member');
members.forEach(member => {
member.addEventListener('click', e => {
e.target.classList.toggle('hight-light');
});
});
.member {
background-color: gray;
}
.hight-light {
background-color: green;
}
<div class="container">
<div class="member">1</div>
<div class="member hight-light">2</div>
<div class="member">3</div>
<div class="member">4</div>
</div>
I have a code snippet I like to keep around to do these kind of things in a single event listener
window.addEvent = (event_type, target, callback) => {
document.addEventListener(event_type, function (event) {
// If the event doesn't have a target
// Or the target doesn't look like a DOM element (no matches method
// Bail from the listener
if (event.target && typeof (event.target.matches) === 'function') {
if (!event.target.matches(target)) {
// If the element triggering the event is contained in the selector
// Copy the event and trigger it on the right target (keep original in case)
if (event.target.closest(target)) {
const new_event = new CustomEvent(event.type, event);
new_event.data = { originalTarget: event.target };
event.target.closest(target).dispatchEvent(new_event);
}
} else {
callback(event);
}
}
});
};
then in your case I'd do this
window.addEvent('click', '#memberA,#memberAA,#memberAAA', (event) => {
event.target.classList.toggle('open');
});
The script runs befor the DOM elements load.
You can put the script as a function inside an $(document).ready such that it runs after all the elements have been loaded.
$(document).ready(
function () {
const memberB = document.querySelectorAll('#memberA, #memberAA, #memberAAA ');
for (let i = 0; i < memberB.length; i++) {
memberB[i].onclick = function () {
//alert(memberB[i])
if (memberB[i].className === "open") {
memberB[i].className = "";
} else {
memberB[i].className = "open";
}
alert(memberB[i].className)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="memberA">A</button>
<button id="memberAA">AA</button>
<button id="memberAAA">AAA</button>
Let me know if this works!
I am trying to convert a small script from javascript to jquery, but I don't know where I should be putting the [i] in jquery?. I am nearly there, I just need someone to point out where I have gone wrong.
This script expands a search input when focused, if the input contains any values, it retains it's expanded state, or else if the entry is removed and clicks elsewhere, it will snap back.
Here is the javascript:
const searchInput = document.querySelectorAll('.search');
for (i = 0; i < searchInput.length; ++i) {
searchInput[i].addEventListener("change", function() {
if(this.value == '') {
this.classList.remove('not-empty')
} else {
this.classList.add('not-empty')
}
});
}
and converting to jquery:
var $searchInput = $(".search");
for (i = 0; i < $searchInput.length; ++i) {
$searchInput.on("change", function () {
if ($(this).value == "") {
$(this).removeClass("not-empty");
} else {
$(this).addClass("not-empty");
}
});
}
Note the key benefit of jQuery that it works on collections of elements: methods such as .on automatically loop over the collection, so you don't need any more than this:
$('.search').on("change", function() {
this.classList.toggle('not-empty', this.value != "");
});
This adds a change event listener for each of the .search elements. I've used classList.toggle as it accepts a second argument telling it whether to add or remove the class, so the if statement isn't needed either.
Currently I have this code to delete a table row:
var remove = document.getElementById(dataID); (this is the id of an object in the row I wish to hide)
if(remove!=null){
var v = remove.parentNode.parentNode.rowIndex;
document.getElementById(tid).deleteRow(v); (tid is the table id, not the row id)
}
However, instead of delete it, I'd just like to hide it. What's a good way to do this?
Also, in the future, I'm going to want to 'unhide' it at user request, so how can I check if it has been hidden? The if(remove!=null) is what checked if a row was already removed, so I'd need something similar.
Thank you for your time.
document.getElementById(tid).children[dataID].style.display = 'none';
You may need -1 on dataID
And block to show it again (or inline or whatever it originally was, for a div it's block).
JQuery:
$('#'+tid+':nth-child('+dataID+')').hide();
My own approach, in plain JavaScript:
function toggleRow(settings) {
// if there's no settings, we can do nothing, so return false:
if (!settings) {
return false;
}
// otherwise, if we have an origin,
// and that origin has a nodeType of 1 (so is an element-node):
else if (settings.origin && settings.origin.nodeType) {
// moving up through the ancestors of the origin, until
// we find a 'tr' element-node:
while (settings.origin.tagName.toLowerCase() !== 'tr') {
settings.origin = settings.origin.parentNode;
}
// if that tr element-node is hidden, we show it,
// otherwise we hide it:
settings.origin.style.display = settings.origin.style.display == 'none' ? 'table-row' : 'none';
}
// a simple test to see if we have an array, in the settings.arrayOf object,
// and that we have a relevant table to act upon:
else if ('join' in settings.arrayOf && settings.table) {
// iterate through that array:
for (var i = 0, len = settings.arrayOf.length; i < len; i++) {
// toggle the rows, of the indices supplied:
toggleRow({
origin: table.getElementsByTagName('tr')[parseInt(settings.arrayOf[i], 10)]
});
}
}
}
// you need an up-to-date browser (you could use 'document.getElementById()',
// but I'm also using 'addEventListener()', so it makes little difference:
var table = document.querySelector('#demo'),
button = document.querySelector('#toggle');
// binding a click event-handler to the 'table' element-node:
table.addEventListener('click', function (e) {
// caching the e.target node:
var t = e.target;
// making sure the element is a button, and has the class 'removeRow':
if (t.tagName.toLowerCase() === 'button' && t.classList.contains('removeRow')) {
// calling the function, setting the 'origin' property of the object:
toggleRow({
origin: t
});
}
});
// binding click-handler to the button:
button.addEventListener('click', function () {
// calling the function, setting the 'arrayOf' and 'table' properties:
toggleRow({
'arrayOf': document.querySelector('#input').value.split(/\s+/) || false,
'table': table
});
});
JS Fiddle demo.
References:
document.querySelector().
e.target.addEventListener().
Node.nodeType.
String.split().
As you've asked for a jQuery solution...how about
var $remove = $('#' + dataID);
if ($remove) {
$remove.closest('tr').closest().hide();
}
?
I am trying to get checked options from a table which are set inline. There is a search function, which sets $(element).css('display','none') on objects in which there is no match with the search. Anyways, this piece of code will only return inline, no matter what the elements are set to. Even if I manually set all of them to display: none in the table itself, the alert will return inline for every single object in the table. Is there any solution to this?
JS code:
function pass_QR() {
var i = 0;
var array = [];
$("input:checkbox:checked").each(function () {
i++;
alert($(this).css('display'));
if ($(this).val() !== 0 && $(this).css('display') === 'inline') {
array.push($(this).val());
}
});
}
Fundamentally, css("display") does work, so something else is going on.
I suspect one of two things:
The checkboxes that you're making display: none are never checked, and so you don't see them in your each loop.
You're not making the checkboxes display: none, but instead doing that to some ancestor element of them. In that case, $(this).is(":visible") is what you're looking for.
Here's an example of #2: Live Copy | Live Source
<div id="ancestor">
<input type="checkbox" checked>
</div>
<script>
$("#ancestor").css("display", "none");
console.log("display property is now: " +
$("input:checkbox:checked").css("display"));
console.log("visible tells us what's going on: " +
$("input:checkbox:checked").is(":visible"));
</script>
...which outputs:
display property is now: inline-block
visible tells us what's going on: false
Applying that to your code:
function pass_QR() {
var i = 0;
var array = [];
$("input:checkbox:checked").each(function () {
i++;
alert($(this).css('display'));
if ($(this).val() !== 0 && $(this).is(':visible')) {
// Change is here -----------------^^^^^^^^^^^^^^
array.push($(this).val());
}
});
}
Side note: Every time you call $(), jQuery has to do some work. When you find yourself calling it repeatedly in the same scope, probably best to do that work once:
function pass_QR() {
var i = 0;
var array = [];
$("input:checkbox:checked").each(function () {
var $this = $(this); // <=== Once
i++;
alert($this.css('display'));
if ($this.val() !== 0 && $this.is(':visible')) {
// Other change is here -------^^^^^^^^^^^^^^
array.push($this.val());
}
});
}
try following:
$("input:checkbox:checked").each(function(i,o){
console.log($(this).css("display"));
});
working fiddle here: http://jsfiddle.net/BcfvR/2/
I have 3 divs with class: wpEdit and onClick: alertName()
<div class="wpEdit" onClick="alertName()">Bruce Lee</div>
<div class="wpEdit" onClick="alertName()">Jackie Chan</div>
<div class="wpEdit" onClick="alertName()">Jet li</div>
When clicked i want to know the Index of class wpEdit of the clicked Div:
function alertName(){
//Something like this
var classIndex = this.className.index; // This obviously dosnt work
alert(classIndex);
}
when clicked on Bruce Lee it should alert : 0
when clicked on Jackie Chan it should alert : 1
when clicked on Jet Li it should alert : 2
I need to know which instance of class="wpEdit" is clicked on
Try this
function clickedClassHandler(name,callback) {
// apply click handler to all elements with matching className
var allElements = document.body.getElementsByTagName("*");
for(var x = 0, len = allElements.length; x < len; x++) {
if(allElements[x].className == name) {
allElements[x].onclick = handleClick;
}
}
function handleClick() {
var elmParent = this.parentNode;
var parentChilds = elmParent.childNodes;
var index = 0;
for(var x = 0; x < parentChilds.length; x++) {
if(parentChilds[x] == this) {
break;
}
if(parentChilds[x].className == name) {
index++;
}
}
callback.call(this,index);
}
}
Usage:
clickedClassHandler("wpEdit",function(index){
// do something with the index
alert(index);
// 'this' refers to the element
// so you could do something with the element itself
this.style.backgroundColor = 'orange';
});
The first thing you might want to address in your code is the inline HTML binding.
You could use document.addEventListener on each element, or rely on event delegation.
The widely most used implementation of event delegation comes with jQuery. If you're already using jQuery, this is the way to go!
Alternatively I've also my own little delegate utility.
const delegate = (fn, selector) => {
return function handler(event) {
const matchingEl = matches(event.target, selector, this);
if(matchingEl != null){
fn.call(matchingEl, event);
}
};
};
const matches = (target, selector, boundElement) => {
if (target === boundElement){
return null;
}
if (target.matches(selector)){
return target;
}
if (target.parentNode){
return matches(target.parentNode, selector, boundElement);
}
return null;
};
This is how you would register the event listener.
document.getElementById('#parent')
.addEventListener('click', delegate(handler, '.wpEdit'));
And this is how you could get the index of the element that generated the event.
const handler = (event) => {
console.log(Array.prototype.indexOf.call(event.currentTarget.children, event.target));
}
Live demo:
const delegate = (fn, selector) => {
return function handler(event) {
const matchingEl = matches(event.target, selector, this);
if (matchingEl != null) {
fn.call(matchingEl, event);
}
};
};
const matches = (target, selector, boundElement) => {
if (target === boundElement) {
return null;
}
if (target.matches(selector)) {
return target;
}
if (target.parentNode) {
return matches(target.parentNode, selector, boundElement);
}
return null;
};
const handler = (event) => {
console.log(Array.prototype.indexOf.call(event.currentTarget.children, event.target));
}
document.getElementById('parent')
.addEventListener('click', delegate(handler, '.wpEdit'));
<div id="parent">
<div class="wpEdit">Bruce Lee</div>
<div class="wpEdit">Jackie Chan</div>
<div class="wpEdit">Jet li</div>
</div>
If you want the index of the div's based on your class wpEdit you can do like this:
HTML:
<div class="wpEdit">Bruce Lee</div>
<div class="wpEdit">Jackie Chan</div>
<div class="other">Other</div>
<div class="wpEdit">Jet li</div>
JS:
$(".wpEdit").bind("click", function(){
var divs = $(".wpEdit");
var curIdx = divs.index($(this));
alert(curIdx);
});
Live example : http://jsfiddle.net/pJwzc/
More information on the index function of jQuery : http://api.jquery.com/index/
Using vanilla javascript, this one works for me:
var wpEdits = document.querySelectorAll(".wpEdit");
for (let i = 0; i < wpEdits.length; i++)
wpEdits[i].addEventListener("click", showID);
function showID(evt) {
for (let i = 0; i < wpEdits.length; i++)
if(wpEdits[i] == evt.target)
alert(i);
}
May not be the best solution though as I am still new to js.
Since I am very new to JS, take the following explanation with a grain of salt:
(Line-1)
This is similar to var wpEdits = document.getElementsByClassName("wpEdit");. It will assign all instances of class="wpEdit" from the html file to the wpEdits variable.
(Line-3 and Line-4)
This two lines will cause any click on the class="wpEdit" to call function showID() defined below.
(Line-6 and Line-10)
When a click event happens, the browser will pass the unique properties of the item being clicked to the evt variable. This then is used in the for loop to compare against all available instances incrementally. The evt.target is used to get to the actual target. Once a match is found, it will alert the user.
To avoid wasting CPU time, running a break; is recommended to exit the loop soon after the match is found.
I could not understand, why people add new functions in previous answers, so...
const wpEdit = document.getElementsByClassName('wpEdit');
for(let i = 0; i < wpEdit.length; i++){
wpEdit[i].addEventListener('click',function(){
alert(i);
});
}
I just added 'click' event, using the loop. And [i] already is the current clicked class index...
FIDDLE