I need some help with the click event, I'm trying to have an individual counter that is incremented by the click event that I have on the img. I've tried many variations, I want to resolve this without using jQuery.
<script async>
var count = 0;
var clickerCount = document.getElementsByClassName('clicker');
var cat = {
count : 0,
counter: function(){
this.count++;
clickerCount.textContent = "Kitten Click Count :" + this.count;
console.log("counter function working");
console.log(cat.count);
}
};
function modifyNum(){
cat.counter();
console.log("modifyNum function working");
}
</script>
</head>
<body>
<div style="display:inline">
<div>
<img src="http://placekitten.com/200/296" id="cat0" onclick="modifyNum();">
<p id='clicker'>Kitten Click Count :</p>
</div>
<div>
<img src="http://placekitten.com/200/296" id='cat1' onclick="modifyNum();">
<p id='clicker'>Kitten Click Count :</p>
</div>
</div>
For a start, you are using id='clicker' in two places (IDs are supposed to be unique), and then using document.getElementsByClassName, which returns nothing because you used an ID and not a class.
Once you do change it to a class, document.getElementsByClassName will return an array of elements. You'll have to use clickerCount[0] and so on, or loop through the array.
This example should work. I've separated the HTML from the Javascript because it looks clearer for me. You can use it as an example to expand / create your own in your own way.
Hope it help
HTML:
<div style="display:inline">
<div>
<img src="http://placekitten.com/200/296" id="1" class="countable">
<span>Kitten Click Count :</span><span id="counter-for-1">0</span>
</div>
<div>
<img src="http://placekitten.com/200/296" id="2" class="countable">
<span>Kitten Click Count :</span><span id="counter-for-2">0</span>
</div>
</div>
JS:
var imagesCountable = document.getElementsByClassName("countable");
var counters = [];
for (var i = 0; i < imagesCountable.length; i++) {
counters[imagesCountable[i].id] = 0;
imagesCountable[i].onclick = function(e) {
document.getElementById("counter-for-" + e.currentTarget.id)
.innerHTML = ++counters[e.currentTarget.id];
}
}
var imagesCountable = document.getElementsByClassName("countable");
var counters = [];
for (var i = 0; i < imagesCountable.length; i++) {
counters[imagesCountable[i].id] = 0;
imagesCountable[i].onclick = function(e) {
var cElem = document.getElementById("counter-for-" + e.currentTarget.id);
cElem.innerHTML = ++counters[e.currentTarget.id];
}
}
<div style="display:inline">
<div>
<img src="http://placekitten.com/200/296" id="1" class="countable">
<span>Kitten Click Count :</span><span id="counter-for-1">0</span>
</div>
<div>
<img src="http://placekitten.com/200/296" id="2" class="countable">
<span>Kitten Click Count :</span><span id="counter-for-2">0</span>
</div>
</div>
I have solved this problem in this JSFiddle!
If you can hardcode the IDs then it's easier in my point o view to just manipulate things by ID.
<div>
<img src="http://placekitten.com/200/296" id="cat0" onclick="counter(0);">
<p id='clicker0'>Kitten Click Count :</p>
<input type="hidden" id="counter0" value="0">
</div>
function counter(id) {
var cnt = parseInt(document.getElementById("counter" + id).value);
cnt++;
document.getElementById("counter" + id).value = cnt;
document.getElementById('clicker' + id).innerHTML = 'Kitten Click Count :' + cnt;
}
It's not the same approach but I find it easy to understand.
Hope it helps.
Ok, so first off you have two elements with the id of 'clicker'. You probably meant for those to be classes and ids. So when you call modifynum() it cant locate those because the class doesn't exists. Second, your JS is loading before your HTML elements. So when the JS gets to this line:
var clickerCount = document.getElementsByClassName('clicker');
It is going to find nothing, even if you correct the class names. So you want to move your JS to the footer of your HTML document, or wrap the code in a method that is called on pageLoad().
I think that should take care of it. Your object, for the most part, looks correct.
Related
How do I get the next element in HTML using JavaScript?
Suppose I have three <div>s and I get a reference to one in JavaScript code, I want to get which is the next <div> and which is the previous.
use the nextSibling and previousSibling properties:
<div id="foo1"></div>
<div id="foo2"></div>
<div id="foo3"></div>
document.getElementById('foo2').nextSibling; // #foo3
document.getElementById('foo2').previousSibling; // #foo1
However in some browsers (I forget which) you also need to check for whitespace and comment nodes:
var div = document.getElementById('foo2');
var nextSibling = div.nextSibling;
while(nextSibling && nextSibling.nodeType != 1) {
nextSibling = nextSibling.nextSibling
}
Libraries like jQuery handle all these cross-browser checks for you out of the box.
Really depends on the overall structure of your document.
If you have:
<div></div>
<div></div>
<div></div>
it may be as simple as traversing through using
mydiv.nextSibling;
mydiv.previousSibling;
However, if the 'next' div could be anywhere in the document you'll need a more complex solution. You could try something using
document.getElementsByTagName("div");
and running through these to get where you want somehow.
If you are doing lots of complex DOM traversing such as this I would recommend looking into a library such as jQuery.
Well in pure javascript my thinking is that you would first have to collate them inside a collection.
var divs = document.getElementsByTagName("div");
//divs now contain each and every div element on the page
var selectionDiv = document.getElementById("MySecondDiv");
So basically with selectionDiv iterate through the collection to find its index, and then obviously -1 = previous +1 = next within bounds
for(var i = 0; i < divs.length;i++)
{
if(divs[i] == selectionDiv)
{
var previous = divs[i - 1];
var next = divs[i + 1];
}
}
Please be aware though as I say that extra logic would be required to check that you are within the bounds i.e. you are not at the end or start of the collection.
This also will mean that say you have a div which has a child div nested. The next div would not be a sibling but a child, So if you only want siblings on the same level as the target div then definately use nextSibling checking the tagName property.
Its quite simple. Try this instead:
let myReferenceDiv = document.getElementById('mydiv');
let prev = myReferenceDiv.previousElementSibling;
let next = myReferenceDiv.nextElementSibling;
There is a attribute on every HTMLElement, "previousElementSibling".
Ex:
<div id="a">A</div>
<div id="b">B</div>
<div id="c">c</div>
<div id="result">Resultado: </div>
var b = document.getElementById("c").previousElementSibling;
document.getElementById("result").innerHTML += b.innerHTML;
Live: http://jsfiddle.net/QukKM/
This will be easy...
its an pure javascript code
<script>
alert(document.getElementById("someElement").previousElementSibling.innerHTML);
</script>
all these solutions look like an overkill.
Why use my solution?
previousElementSibling supported from IE9
document.addEventListener needs a polyfill
previousSibling might return a text
Please note i have chosen to return the first/last element in case boundaries are broken.
In a RL usage, i would prefer it to return a null.
var el = document.getElementById("child1"),
children = el.parentNode.children,
len = children.length,
ind = [].indexOf.call(children, el),
nextEl = children[ind === len ? len : ind + 1],
prevEl = children[ind === 0 ? 0 : ind - 1];
document.write(nextEl.id);
document.write("<br/>");
document.write(prevEl.id);
<div id="parent">
<div id="child1"></div>
<div id="child2"></div>
</div>
You can use nextElementSibling or previousElementSibling properties
<div>
<span id="elem-1">
span
</span>
</div>
<div data-id="15">
Parent Sibling
</div>
const sp = document.querySelector('#elem-1');
let sibling_data_id = sp.parentNode.nextElementSibling.dataset.id;
console.log(sibling_data_id); // 15
Tested it and it worked for me. The element finding me change as per the document structure that you have.
<html>
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<form method="post" id = "formId" action="action.php" onsubmit="return false;">
<table>
<tr>
<td>
<label class="standard_text">E-mail</label>
</td>
<td><input class="textarea" name="mail" id="mail" placeholder="E-mail"></label></td>
<td><input class="textarea" name="name" id="name" placeholder="E-mail"> </label></td>
<td><input class="textarea" name="myname" id="myname" placeholder="E-mail"></label></td>
<td><div class="check_icon icon_yes" style="display:none" id="mail_ok_icon"></div></td>
<td><div class="check_icon icon_no" style="display:none" id="mail_no_icon"></div></label></td>
<td><div class="check_message" style="display:none" id="mail_message"><label class="important_text">The email format is not correct!</label></div></td>
</tr>
</table>
<input class="button_submit" type="submit" name="send_form" value="Register"/>
</form>
</body>
</html>
var inputs;
document.addEventListener("DOMContentLoaded", function(event) {
var form = document.getElementById('formId');
inputs = form.getElementsByTagName("input");
for(var i = 0 ; i < inputs.length;i++) {
inputs[i].addEventListener('keydown', function(e){
if(e.keyCode == 13) {
var currentIndex = findElement(e.target)
if(currentIndex > -1 && currentIndex < inputs.length) {
inputs[currentIndex+1].focus();
}
}
});
}
});
function findElement(element) {
var index = -1;
for(var i = 0; i < inputs.length; i++) {
if(inputs[i] == element) {
return i;
}
}
return index;
}
that's so simple
var element = querySelector("div")
var nextelement = element.parentElement.querySelector("div+div")
Here is the browser supports https://caniuse.com/queryselector
I want to dynamically add the id and for attribute for each input and label element.
<div id="splash">
<div class="tab">
<input id="tab-1">
<label for="tab-1"><label>
</div>
<div class="tab">
<input id="tab-2">
<label for="tab-2"><label>
</div>
<div class="tab">
<input id="tab-3">
<label for="tab-3"><label>
</div>
</div>
So basically I would want the id for the input to be tab-# with the # increasing by 1 for each input field and the same for the "for=" attribute for the label.
It's super easy. Just iterate through each .tab, using each's index argument, and modify the attributes of the elements.
$('.tab').each(function (index) {
var tabName = 'tab-' + (index + 1);
$('input', this).attr('id', tabName);
$('label', this).attr('for', tabName);
});
Jsbin: http://jsbin.com/rawatag/4/edit?html,js,output
Ok.
I won't give you a straight answer but this should be more useful in future.
Basically make the container <div id=splash>
Then run this command document.getElementById("parentID").innerHTML += "Something here"
This will add the content (pay attention to. The += sign) to the div (splash)
Then, just wrap this in a loop using a counter to get the desired result
Eg: ...innerHTML += "<div id=tab-" + counter + "></div>"
Note that this can be done in raw JS. No JQuery required.
No need for jQuery here:
es5 (jsfiddle)
function assignInputsAndLabels(root) {
var children = root.children;
var tabNumber = 1;
for (var i = 0; i < children.length; i++) {
if (children[i].classList.contains('tab')) {
children[i].getElementsByTagName('input')[0].setAttribute('id', 'tab-' + tabNumber);
children[i].getElementsByTagName('label')[0].setAttribute('for', 'tab-' + tabNumber);
tabNumber++;
}
}
}
assignInputsAndLabels(document.getElementById('splash'));
es6
function assignInputsAndLabels(root) {
const children = root.children;
let tabNumber = 1;
for (let i = 0; i < children.length; i++) {
if (children[i].classList.contains('tab')) {
children[i].getElementsByTagName('input')[0].setAttribute('id', `tab-${tabNumber}`);
children[i].getElementsByTagName('label')[0].setAttribute('for', `tab-${tabNumber}`);
tabNumber++;
}
}
}
assignInputsAndLabels(document.getElementById('splash'));
The parameter to the function is the wrapper of the elements that have the class of tab. In your case, you'd pass in the DOM node of the element with id of splash. So you'd call the function like this:
assignInputsAndLabels(document.getElementById('splash'));
I have done it using javascript.Check it below
function init(){
var sel = document.getElementsByClassName("tab");
var i=1;
for(let obj of sel){
var attr = "tab-"+i;
obj.getElementsByTagName('input')[0].setAttribute("id",attr);
obj.getElementsByTagName('label')[0].setAttribute("for",attr);
i++;
}
}
addEventListener("load",init);
<div class="tab">
<input type="text">
<label></label>
</div>
<div class="tab">
<input type="text">
<label></label>
</div>
I dynamically create a form. There is an add line button that adds a new line that includes a delete line button.
I originally wrote this in angular, and I was able to pass "$index" into the function to remove the specific line.
I am now rewriting my code in pure js, and my question is: How can I go about implementing this same functionality?
The example for deleting elements by index as per your requirement can be found in this jsfiddle : https://jsfiddle.net/ChaitanyaMunipalle/9z73rfjx/2/. I assume you will take care of adding lines & delete buttons dynamically. It contains only deletion.
As you have not given any code, I assumed the html would look like the below one:
<div id="lines">
<div class="line-item">
<input type="text" name="line-value"/> <button class="delete-line">Delete</button>
</div>
<div class="line-item">
<input type="text" name="line-value"/> <button class="delete-line">Delete</button>
</div>
<div class="line-item">
<input type="text" name="line-value"/> <button class="delete-line">Delete</button>
</div>
</div>
You have to add event listeners to delete buttons. And you have to use closure to save the index of the button clicked.
var deleteItem = function(index) {
var divElements = document.getElementsByClassName("line-item");
for (var i = 0; i < divElements.length; i++) {
if (i == index) {
divElements[i].parentNode.removeChild(divElements[i]);
break;
}
}
};
var deleteButtons = document.getElementsByClassName("delete-line");
for (var i = 0; i < deleteButtons.length; i++) {
(function(index){
deleteButtons[i].addEventListener('click', function() {
deleteItem(index);
}, false);
})(i);
}
I don't quite understand your setup, but removing a div is just
parentNode.removeChild(yourDiv)
If you only have the parentNode but know the index of the div you want to delete, then
parentNode.removeChild(parentNode.children[i])
`<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.removeChild(child);
</script>`
This a example in jsfiddle:
https://jsfiddle.net/AlfonsoRamirez9/ttj1sLo5/
I hope help you :)
I wish to know the best way to write only once the same thing and repeat inside the same page. For example:
<div>
<p id="description1"></p>
</div>
<div>
<p id="description1"></p>
</div>
--
I wish to write only one time the description1 inside the body. I think this could be achieved using the DOM.
Put the elements in the same class using the class attribute, then get the list of all elements using the getElementsByClassName() DOM function. You can then go over the list using a for loop.
[].forEach.call(document.getElementsByClassName("description"), function(elem) {
elem.innerHTML = "StackOverflow saved my day!";
});
You can even put the text in all elements of the same class using no JavaScript and only CSS by using the content attribute.
First of all, the ID field should be unique per element.
If you give all the tags a class <p class="description"></p> then you can use jQuery to set them all by calling:
$('.description').text('This is the text')
In javascript:
var elements = document.getElementsByClassName("description");
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = "This is the text.";
}
Have a look at the solutions proposed here
How to repeat div using jQuery or JavaScript?
this one seems to work pretty well:
html:
<div id="container">data</div>
js:
var container = document.getElementById('container');
function block(mClass, html) {
//extra html you want to store.
return '<div class="' + mClass + '">' + html + '</div>';
}
// code that loops and makes the blocks.
// first part: creates var i
// second: condition, if 'i' is still smaller than three, then loop.
// third part: increment i by 1;
for (var i = 0; i < 3; i++) {
// append the result of function 'block()' to the innerHTML
// of the container.
container.innerHTML += block('block', 'data');
}
JSFIDDLE
Just added with a code by using
getElementsByClassName()
`<html>
<body>
<div class="example">First div element with class="example".</div>
<p class="example">Second paragraph element with class="example".</p>
<p>Click the button to change the text of the first div element with class="example" (index 0).</p>
<button onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> The getElementsByClassName() method is not supported in Internet Explorer 8 and earlier versions.</p>
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
for(var i=0;i< x.length;i++)
x[i].innerHTML = "Hello World!";
}
</script>
</body>
</html>`
If you wish to keep id, change your code like this :
script :
var pcount = 2// # p
var desc = document.getElementById('description1');
for(i=0; i<pcount;i++){
document.getElementById('description' + i).innerHTML = desc;
}
html
<div>
<p id="description1"></p>
</div>
<div>
<p id="description2"></p>
</div>
two elements cannot have same id but can have same class
<head>
<script>
var x = document.getElementsByClassName("description");
for (var i = 0; i < x.length; i++) {
x[i].innerHTML = "This is the text.";
}
</script>
<style>
.description1 { // this will apply the same style to all elements having class as description1
text-align: center;
color: red;
}
</style>
</head>
<body>
<div>
<p class="description1"></p>
</div>
<div>
<p class="description1"></p>
</div>
</body>
See the script tag. this solves your problem
I'm working on something really simple, a short quiz, and I am trying to make the items I have listed in a 2-d array each display as a <li>. I tried using the JS array.join() method but it didn't really do what I wanted. I'd like to place them into a list, and then add a radio button for each one.
I have taken the tiny little leap to Jquery, so alot of this is my unfamiliarity with the "syntax". I skimmed over something on their API, $.each...? I'm sure this works like the for statement, I just can't get it to work without crashing everything I've got.
Here's the HTML pretty interesting stuff.
<div id="main_">
<div class="facts_div">
<ul>
</ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me">
</form>
</div>
And, here is some extremely complex code. Hold on to your hats...
$(document).ready (function () {
var array = [["Fee","Fi","Fo"],
["La","Dee","Da"]];
var q = ["<li>Fee-ing?","La-ing?</li>"];
var counter = 0;
$('.myBtn').on('click', function () {
$('#main_ .facts_div').text(q[counter]);
$('.facts_div ul').append('<input type= "radio">'
+ array[counter]);
counter++;
if (counter > q.length) {
$('#main_ .facts_div').text('You are done with the quiz.');
$('.myBtn').hide();
}
});
});
Try
<div id="main_">
<div class="facts_div"> <span class="question"></span>
<ul></ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me" />
</form>
</div>
and
jQuery(function ($) {
//
var array = [
["Fee", "Fi", "Fo"],
["La", "Dee", "Da"]
];
var q = ["Fee-ing?", "La-ing?"];
var counter = 0;
//cache all the possible values since they are requested multiple times
var $facts = $('#main_ .facts_div'),
$question = $facts.find('.question'),
$ul = $facts.find('ul'),
$btn = $('.myBtn');
$btn.on('click', function () {
//display the question details only of it is available
if (counter < q.length) {
$question.text(q[counter]);
//create a single string containing all the anwers for the given question - look at the documentation for jQuery.map for details
var ansstring = $.map(array[counter], function (value) {
return '<li><input type="radio" name="ans"/>' + value + '</li>'
}).join('');
$ul.html(ansstring);
counter++;
} else {
$facts.text('You are done with the quiz.');
$(this).hide();
}
});
//
});
Demo: Fiddle
You can use $.each to iterate over array[counter] and create li elements for your options:
var list = $('.facts_div ul');
$.each(array[counter], function() {
$('<li></li>').html('<input type="radio" /> ' + this).appendTo(list);
}
The first parameter is your array and the second one is an anonymous function to do your action, in which this will hold the current element value.
Also, if you do this:
$('#main_ .facts_div').text(q[counter]);
You will be replacing the contents of your element with q[counter], losing your ul tag inside it. In this case, you could use the prepend method instead of text to add this text to the start of your tag, or create a new element just for holding this piece of text.