It's easy to change class 'day' with addEventListener if I specify it with day[2], day[3] etc.
I don't really want to write all that code for each of them, how could I catch the class' order number "day[?]" when it's clicked, so I could use it in changeDate().
Parts of current code:
var day = document.getElementsByClassName("day");
day[2].addEventListener("click", changeDate);
function changeDate() {
console.log("hit");
}
<li class="day">1</li>
<li class="day">2</li>
<li class="day">3</li>
In the changeData() function, you are able to access to this. It's the associated <li> (which were clicked), so use this.innerHTML to get the number of the day.
You can use the following code using standard javascript to find and attach click event handlers to all .day HTML elements.
<body>
<li class="day">1</li>
<li class="day">2</li>
<li class="day">3</li>
...
</body>
<script>
var dayArray = [];
window.onload = function(){
dayArray = document.getElementsByClassName("day");
for (var i = 0; i < dayArray.length; i++) {
dayArray[i].addEventListener('click', changeDate, false);
}
};
function changeDate(evt){
console.log(this); // Here 'this' refers to the clicked HTML element
}
</script>
Hope this helps.
Get all of the classes and loop through them to add listeners, like this:
var days = document.getElementsByClassName('day');
for(var i = 0; i < days.length; i++){
days[i].addEventListener('click', changeDate);
}
EDIT: sorry, missed the last line: Your change date function can then include the following:
function changeDate(){
var day = this.textContent;
};
Now the day variable in the text inside the element that was clicked.
Addition to #fauxserious answer you could try this:
var days = document.getElementsByClassName('day');
for(var i = 0; i < days.length; i++){
days[i].addEventListener('click', changeDate);
}
function changeDate(){
console.log('Clicked day ' + this.innerHTML);
}
Related
I have a svg map and I am putting that into object and I am trying to create all path with id clickable.
For that I am doing this to get svg object :
let a = document.getElementById("biharsvg")
And I am putting that into svg doc like this:
var svgDoc = a.contentDocument;
And now I am getting all the values of certain class using this:
let de = svgDoc.getElementsByClassName("fil0");
I can also get the attribute id value using this:
var i;
for (i = 0; i < de.length; i++) {
var j = de[i].getAttribute("id");
console.log(j);
}
I want to add a click event on each attribute id and get the value when I am doing this:
var i;
for (i = 0; i < de.length; i++) {
var j = de[i].getAttribute("id");
console.log(j);
svgDoc.getElementById(j).onclick = function() {
modal.style.display = "block";
console.log(this.getAttribute("id"));
}
}
This is working fine and I am getting all the values but in jquery I can use this:
$(de).click(function(){
alert(this.getAttribute("id"));
});
Is there any way I can use something like this in javascript without loop. My question is what is the best possible way to make this work in javascript.
The javascript version for jQuery's
$(de).click(function(){
alert(this.getAttribute("id"));
});
would be something like
Array.from(de).forEach( function(el){
el.addEventListener('click', function() {
alert(this.getAttribute("id"));
// or "this.id" should work too
});
});
To be noted, when doing $(de).click(function(){...} with jQuery, it also loops, internally.
And as commented, with arrow functions you could shorten the code even more
Array.from(de).forEach(el => el.addEventListener('click', function () {...}))
var de = document.querySelectorAll('span');
Array.from(de).forEach(el => el.addEventListener('click', function () {
alert(this.id);
}))
span {
display: inline-block;
padding: 20px;
margin: 0 5px;
border: 1px dotted black;
}
span::after {
content: attr(id)
}
<span id="nr1">click </span>
<span id="nr2">click </span>
<span id="nr3">click </span>
Updated based on a comment.
The main difference between your existing loop and the above is, the above is more efficient, with a cleaner/shorter code.
In your original loop
var i;
for (i = 0; i < de.length; i++) {
var j = de[i].getAttribute("id");
svgDoc.getElementById(j).onclick = function() {
modal.style.display = "block";
console.log(this.getAttribute("id"));
}
}
you iterate through the element array de, get its id and then make a new call using getElementById to get the element you already have.
With the kept syntax/logic, your existing code could been simplified to something like this
for (var i = 0; i < de.length; i++) {
de.onclick = function() {
modal.style.display = "block";
console.log(this.getAttribute("id"));
}
}
I just want to show an alternative way, pointed out by CBroe, where a click on the document is checked for its event target:
let de = Array.from(mylist.getElementsByClassName("fil0"));
document.addEventListener('click', function(e) {
const el = e.target;
if (de.indexOf(el) < 0) return false;
alert(el.innerHTML);
});
<ul id="mylist">
<li>one</li>
<li class="fil0">two*</li>
<li class="fil0">three*</li>
</ul>
<p>* has click event assigned indirectly</p>
This has the additional benefit that it only uses a single handler function, and if the indexOf() condition is changed to something like classList.contains(), it will even work for elements that don't exist yet.
I find for..of to be the most convenient and readable syntax:
for (const element of svgDoc.getElementsByClassName("fil0")) {
console.log(element.id);
}
I'm trying to apply the onclick event with JavaScript to the following elements:
<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>
If I click on the first element (with index [0]) then this works, but I
need this event applicable for all classes:
document.getElementsByClassName('abc')[0].onclick="function(){fun1();}";
function fun1(){
document.getElementsByClassName('abc').style.color="red";
}
.onclick does not expect to receive a string, and in fact you don't need an extra function at all.
However, to assign it to each element, use a loop, like I'm sure you must have learned about in a beginner tutorial.
var els = document.getElementsByClassName('abc');
for (var i = 0; i < els.length; i++) {
els[i].onclick = fun1;
}
function fun1() {
this.style.color = "red";
}
<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>
To expand on the solution provided by #rock star I added two small additions to the function. First it is better to add / reemove a class (with an associated style rule) to an element than directly applying the stylerule to the element.
Secondly - on the click event - this will now remove the red class (and therefore style) from the previously selected element and add it to the new element. This will allow only one element to be red at a time (in the original solution any element that was clicked would become red).
var els = document.getElementsByClassName('abc');
for (var i = 0; i < els.length; i++) {
els[i].onclick = fun1;
}
function fun1() {
var oldLink = document.getElementsByClassName('red')[0];
if(oldLink) {oldLink.classList.remove('red')};
this.classList.add('red');
}
.red {
color:red;
}
<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>
This works:
<body>
<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>
<script>
var elements = document.getElementsByClassName('abc');
for(var i = 0, max = elements.length; i < max; i += 1) {
var clickedElement = elements[i];
clickedElement.onclick=function (){
fun1(this);
};
}
function fun1(element){
element.style.color="red";
}
</script>
</body>
So I have a Javscript that can retrieve the id from onClick, but it only selects the first div with an id. The problem is that I have multiple unique id's that are generated in php and then saved in mysql database. The id's are unique but I need my onClick to retrieve the id in the div block.
function postFunction() {
var i;
var x;
for (i = 0; i< x.length; i++)
x = document.getElementsByClassName("post")[0].getAttribute("id");
//alert(this.id);
alert(x);
}
Is there a way to select id per code block?
I see you have the jQuery tag in your question. Try this:
function postFunction() {
var ids = []; //in case you need to have all ids;
$('.post').each(function() {
var id = $(this).attr('id');
ids.push(id); //Store the id in the array
alert(id);
});
console.log(ids); //Show all ids.
}
Using Jquery will make life easier.
var h=[];
$("div").each(function(){
h.push($(this).attr('id'));
});
alert(h);
You will get a array of all div ID's.
You need to get the elements, and then loop over them (currently your loop code doesn't do anything)
function postFunction() {
var postEls = document.getElementsByClassName('post'),
postElsCount = postEls.length;
for (var i = 0; i < postElsCount; i++) {
alert(postEls[i].id);
}
}
Here's a fiddle
jQuery will always ease such operations but you can also achieve the same using vanilla javascript. It takes effort & time because of cross browser support for javascript varies much but it's worth to give a try.
function postFunction() {
var ids = [];
var x = document.getElementByClassName('post');
for (var i = 0; i < x.length; i++) {
var temp = x[i].getAttribute("id");
ids.push(temp);
}
console.log(ids)
}
Without jQuery:
function postFunction() {
var ids = Array.prototype.map.call(document.getElementsByClassName("post"), function(elem) {
return elem.id
});
console.log(ids.join(", "));
}
getElementsByClassName() returns a list of all HTML elements with the provided class name. In your loop, you are only ever alerting the first element returned at index [0].
Try:
var x = document.getElementsByClassName("post");
for (var i = 0; i < x.length; i = i + 1) {
alert(x[i].getAttribute("id"));
}
<!DOCTYPE html>
<html lang="en">
<div id="blah1" class="post"></div>
<div id="blah2" class="post"></div>
<div id="blah3" class="post"></div>
<div id="blah4" class="post"></div>
<div id="blah5" class="post"></div>
</html>
It is a calculator which has spans from which I want to take a values(1,2,3, etc.) and two fields: First for displaying what user is typing and the second is for result of calculation.
The question how to get values so when I click on spans it will show it in the second field
Here is the code.
http://jsfiddle.net/ovesyan19/vb394983/2/
<span>(</span>
<span>)</span>
<span class="delete">←</span>
<span class="clear">C</span>
<span>7</span>
<span>8</span>
<span>9</span>
<span class="operator">÷</span>
....
JS:
var keys = document.querySelectorAll(".keys span");
keys.onclick = function(){
for (var i = 0; i < keys.length; i++) {
alert(keys[i].innerHTML);
};
}
var keys = document.querySelectorAll(".keys span");
for (var i = 0; i < keys.length; i++) {
keys[i].onclick = function(){
alert(this.innerHTML);
}
}
keys is a NodeList so you cannot attach the onclick on that. You need to attach it to each element in that list by doing the loop. To get the value you can then simple use this.innerHTML.
Fiddle
This should get you started.. you need to get the value of the span you are clicking and then append it into your result field. Lots more to get this calculator to work but this should get you pointed in the right direction.
Fiddle Update: http://jsfiddle.net/vb394983/3/
JavaScript (jQuery):
$(".keys").on("click","span",function(){
var clickedVal = $(this).text();
$(".display.result").append(clickedVal);
});
You can set a click event on the span elements if you use JQuery.
Eg:
$("span").click(
function(){
$("#calc").val($("#calc").val() + $(this).text());
});
See:
http://jsfiddle.net/vb394983/6/
That's just to answer your question but you should really give the numbers a class such as "valueSpan" and the operators a class such as "operatorSpan" and apply the events based on these classes so that the buttons behave as you'd expect a calculator to.
http://jsfiddle.net/vb394983/7/
var v="",
max_length=8,
register=document.getElementById("register");
// attach key events for numbers
var keys = document.querySelectorAll(".keys span");
for (var i = 0; l = keys.length, i < l; i++) {
keys[i].onclick = function(){
cal(this);
}
};
// magic display number and decimal, this formats like a cash register, modify for your own needs.
cal = function(e){
if (v.length === self.max_length) return;
v += e.innerHTML;
register.innerHTML = (parseInt(v) / 100).toFixed(2);
}
Using JQuery will make your life much easier:
$('.keys span').click(function() {
alert(this.innerHTML);
});
i have a page around 500 div as below.
<div onclick='test()' class='test>
<ul class='innermenu'>
<li>1</li>
.....
</ul>
</div>
when the test function is called it need to hide the menu (innermenu) who calls that function.
my problems are
uniquely identify the div without using id
How to hide only the particular ul alone.
OK, first the quick fix, though it is not the best way to use JS on your page:
Change the call to this:
<div onclick="test(this);" class="test">
Then, in test, use this:
function test(el){
var uls = el.getElementsByTagName('ul');
for(var i = 0; i < uls.length; i++){
if(uls[i].className == 'innermenu'){
uls[i].style.display = "none";
break;
}
}
}
This will hide just the child ul of the div that is clicked.
A better way
OK, for the longer answer. Either attach the events after the fact using attachEvent and addEventListener or use a library like jQuery to help you out. Here is the raw solution:
Set up your HTML this way (no onclick):
<div class="test">
And then at the very end of your HTML put this:
<script type="text/javascript">
var divs = document.getElementsByTagName('div');
function test(){
var uls = this.getElementsByTagName('ul');
for(var i = 0; i < uls.length; i++){
if(uls[i].className == 'innermenu'){
uls[i].style.display = "none";
break;
}
}
};
for(var i = 0; i < divs.length; i++){
var div = divs[i];
if(div.className !== "test") continue;
if(window.addEventListener){
div.addEventListener( 'click', test, true ); //FF, Webkit, etc
} else if (window.attachEvent) {
div.attachEvent('onclick', test); // IE
} else {
div.onclick = test; // Fallback
}
}
</script>
Now, you don't have JavaScript code in your HTML, and you can get rid of the extra parameter on the test function.
There is a method
document.getElementsByClassName
but it isn't supported in all browsers.
javascript
function test(elem)
{
var childElem = elem.children[0];
childElem.style.display = 'none';
}
<div onclick='test(this)' class='test'>
<ul class='innermenu'>
<li>1</li>
<li>2</li>
</ul>
</div>
If you can use jQuery then you can do something like this
$("div.test").click(function(){
$(this).find("ul.innermenu").hide();
});
If you don't want assign ids, you can try this to hide the div which gets clicked:
<div onclick="hideMe(this);" class='test>
<script>
function hideMe(elem)
{
elem.style.display = 'none';
}
</script>
Try passing "this" as parameter:
<div onclick='test(this)' class='test>
<ul class='innermenu'>
<li>1</li>
.....
</ul>
function test(sender) {
//sender is DOM element that is clicked
alert(sender.id);
}
If getElementsByClassName is not supported by all browsers as mentioned by #rahul, you can iterate through the dom and find it yourself - provided there is only one <ul> with class name "innermenu"
var uls = document.body.getElementsByTagName("ul");
var len = uls.length;
for(var i = 0; i < len; i++)
{
var ul = uls.item(i);
if(ul.getAttribute("class") == "innermenu")
{
ul.style.display = "none";
break;
}
}