JavaScript onclick event on elementByClassName [duplicate] - javascript

This question already has answers here:
Javascript infamous Loop issue? [duplicate]
(5 answers)
Closed 7 years ago.
I have following mark up and I am trying to run a javascript function once clicked. So far I haven't faced any success. Plz help -
<div class='color-bar'></div>
<div class='color-bar'></div>
<div class='color-bar'></div>
<div class='color-bar'></div>
var ColorBars = document.getElementsByClassName("color-bar");
var charts = $("#line-container").highcharts();
var series;
var colorIndex = new Array();
for(var i = 0; i < ColorBars.length; i++){
ColorBars[i].onclick = function(){
hideColor(i);
}
}
function hideColor(index){
var charts = $("#line-container").highcharts();
var series = charts.series[index];
if(series.visible){
series.hide();
}
else{
series.show();
}
}
The problem I am having is figuring out which color-bar user has clicked. Is it first one, 2nd or 3rd. Based on this I need to fire the hideColor function.
Thanks a lot. Best regards, jahid

You need to give you colorbars ids:
<div class='color-bar' id="colorbar1"></div>
<div class='color-bar' id="colorbar2">></div>
<div class='color-bar' id="colorbar3">></div>
<div class='color-bar' id="colorbar4">></div>
And then you can check with:
ColorBars[i].id == X

Related

Why are my checkboxes not remaining ticked? [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Using document.getElementById() inside object, works in JSFiddle, TypeError in actual. Why?
(3 answers)
Closed 2 days ago.
I have been trying to create a completion tracker where I can use checkboxes to track tasks I have to do. I would like the checkboxes to remain checked. However the only place where I can get this to happen with my current code is in codepen.io . When I open with live server or open in browser using the extensions in vscode, it has not remembered that I have checked the boxes. How can I fix this?
This is my javascript file (app.js):
let boxes = document.getElementsByClassName('box').length;
function save() {
for(let i = 1; i <= boxes; i++){
var checkbox = document.getElementById(String(i));
localStorage.setItem("checkbox" + String(i), checkbox.checked);
}
}
//for loading
for(let i = 1; i <= boxes; i++){
if(localStorage.length > 0){
var checked = JSON.parse(localStorage.getItem("checkbox" + String(i)));
document.getElementById(String(i)).checked = checked;
}
}
window.addEventListener('change', save);
And this is the html file:
<script src="app.js"></script>
<input type="checkbox" id="1" class="box">checkbox1</input><br>

how to remove an image in javascript by clicking on it with remove method [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 2 years ago.
i am trying to remove image by clicking on it after i create 'img' element using createElement but i cant remove the image , whats wrong with the removes function in my code ?
here is my code :
function generateCat(){
var image = document.createElement('img')
var div = document.getElementById('flex-cat-gen');
image.src= ('image.jpg');
div.appendChild(image);
}
document.getElementsByTagName('img').onclick = function removes() {
document.getElementsByTagName('img').remove();
}
You should try like this.You have to add an Eventlistener for click event.Also see document.getElementsByTagName(),
Method returns a live HTMLCollection of elements with the given tag
name
function generateCat() {
var image = document.createElement('img')
var div = document.getElementById('flex-cat-gen');
image.src = ('https://cdn.nikkiflower.com/assets/uploads/product_image/114/small/1575008384_0.jpg');
div.appendChild(image);
let tags = document.getElementsByTagName('img');
for (let i = 0; i < tags.length; i++) {
tags[i].addEventListener("click", function() {
this.remove()
})
}
}
<div id="flex-cat-gen">
</div>
<button class="btn btn-warning" onclick="generateCat()">Generat Cat</button>

Javascript Eventlistener Loop with own attributes [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 5 years ago.
i have an problem. I have an div element within x subelements (buttons etc) and the subelements i will add an eventlistener with a loop, i have provided a fiddle:
<button test="page1">page1</button>
<button test="page2">page2</button>
<br>
<button test2="page1">page1</button>
<button test2="page2">page2</button>
var location = document.querySelectorAll("[test]");
var location2 = document.querySelectorAll("[test2]");
location.forEach(function(e1, e2){
location[e2].addEventListener("click", function(){
alert(location[e2].getAttribute("test"));
});
});
for(var i = 0; i < location2.length; i++){
location2[i].addEventListener("click", function(){
alert(location2[i].getAttribute("test2"));
});
}
https://jsfiddle.net/zeus1309/jqL8b0rt/
The version with foreach works. but the one with for not.
I dont understand why.
Instead of location2[i].getAttribute("test2") use this.getAttribute("test2").
Note: Inside the forEach() function, you don't have to use both arguments.
var location = document.querySelectorAll("[test]");
var location2 = document.querySelectorAll("[test2]");
location.forEach(function(e){
e.addEventListener("click", function(){
alert(e.getAttribute("test"));
});
});
for(var i = 0; i < location2.length; i++){
location2[i].addEventListener("click", function(){
alert(this.getAttribute("test2"));
});
}
<button test="page1">page1</button>
<button test="page2">page2</button>
<br>
<button test2="page1">page1</button>
<button test2="page2">page2</button>

in javascript, function in loop can't access the loop scope variable [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
it is based on jQuery Easy UI
Assume that here is the HTML code
<div id="menu" class="easyui-menu" style="width:120px;">
<div>New</div>
<div>
<span>Open</span>
<div style="width:150px;">
<div><b>Word</b></div>
<div>Excel</div>
<div>PowerPoint</div>
</div>
</div>
<div data-options="iconCls:'icon-save'">Save</div>
<div class="menu-sep"></div>
<div>Exit</div>
</div>
The problem is if you setup the menu in the loop, the function always triggered by the last statement, i.e. i always equals to 4 in console.log(itemLabel + i + "is selected.");
$(function(){
var jqMenu = $("#menu");
for (var i = 0; i < 5; i++) {
var itemLabel = "item " + i;
// correct
var onclickFunction = function(){
console.log(itemLabel + i + "is selected.");
}
jqMenu.menu("appendItem",{
"text":itemLabel,
"onclick": function(){
console.log(itemLabel + " is selected.");
}
});
}
})
$(document).bind('contextmenu',function(e){
e.preventDefault();
$("#menu").menu('show', {
left: 200,
top: 100
});
});
the problem you are facing above can be solved using closures. I had this challenge once and solved it using closures.
Change your code to match this. Try using this format in your code.
for (var i = 0; i < 5; i++) {
(function(x){
console.log(x);
})(i);
}
Yeah, use a function to create a closure would help, also check out this answer: https://stackoverflow.com/a/3572616/883571
Personally I would suggest using forEach to bypass the problem:
[1,2,3,4,5].forEach(function(i) {
console.log(i)
});

How to make this code work? (Javascript) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have the following code:
var dateClasses = $('.dateClass'); // array of all your dateClasses
var contentClasses = $('.contentClass'); // array of all your contentClasses
for(var i=0; i< Math.min(dateClasses.length,contentClasses.length); i++) {
var frame = $("<div>", {class: "frame"}); // create your frame node
var timeLineDate = $("<span>",{class: "timeline-date"});
var timeLineContent = $("<div>",{class: "timeline-content"});
//Append DateClass to your timeline-data:
timeLineData.append(dateClasses[i]);
//Append ContentClass to your timeline-content:
timeLineContent.append(contentClasses[i]);
//Append all to your frame
frame.append(timeLineData);
frame.append(timeLineContent);
}
And:
<span class="dateClass">date1</span>
<span class="dateClass">date2</span>
<span class="dateClass">date3</span>
<div class="contentClass">content1</div>
<div class="contentClass">content2</div>
<div class="contentClass">content3</div>
But I'm not sure why it wouldn't work, any advise? :/
http://jsfiddle.net/8qrLh2wz/
Thanks for your time
Edit:
I apologize to everyone, I submitted the post too quickly I totally deserve the downvotes.
What I'd like to do is indeed (as one of you mentioned) move the dateClass elements to timeline-date, and contentClass to timeline-content. However I need one frame per dateClass and contentClass group of elements: that means there should be 3 frame in total
I think what you are trying to do is to move the dateClass elements to timeline-date and contentClass to timeline-content.
But in your code you are creating new elements, but they are not added to the dom so try
var dateClasses = $('.dateClass'); // array of all your dateClasses
var contentClasses = $('.contentClass'); // array of all your contentClasses
$('.frame .timeline-date').append(dateClasses);
$('.frame .timeline-content').append(contentClasses);
Demo: Fiddle
If you want to keep your loop
var dateClasses = $('.dateClass'); // array of all your dateClasses
var contentClasses = $('.contentClass'); // array of all your contentClasses
var timeLineData =$('.frame .timeline-date');
var timeLineContent =$('.frame .timeline-content');
for (var i = 0; i < Math.min(dateClasses.length, contentClasses.length); i++) {
//Append DateClass to your timeline-data:
timeLineData.append(dateClasses[i]);
//Append ContentClass to your timeline-content:
timeLineContent.append(contentClasses[i]);
}
Demo: Fiddle
First at all, your question is not clear, what it should do?
Second, there is a typo on your code, your var name is "timeLineDate", but you're calling timeLineData twice.
Updated
<span class="dateClass">date1</span>
<span class="dateClass">date2</span>
<span class="dateClass">date3</span>
<div class="contentClass">content1</div>
<div class="contentClass">content2</div>
<div class="contentClass">content3</div>
var dateClasses = $('.dateClass'); // array of all your dateClasses
var contentClasses = $('.contentClass'); // array of all your contentClasses
var countElements = Math.min(dateClasses.length, contentClasses.length);
for(var i = 0; i < countElements; i++) {
var frame = $("<div>", {class: "frame"}); // create your frame node
var timeLineDate = $("<div>",{class: "timeline-date"});
var timeLineContent = $("<div>",{class: "timeline-content"});
//Append DateClass to your timeline-data:
timeLineDate.append(dateClasses[i]);
//Append ContentClass to your timeline-content:
timeLineContent.append(contentClasses[i]);
//Append all to your frame
frame.append(timeLineDate);
frame.append(timeLineContent);
$("body").append(frame);
}
http://jsfiddle.net/j8229w4v/2/

Categories