Adding click event to HTML5 template - javascript

How do you add a click event to a html5 template tag?
The following never registers a click event with the image:
<!doctype html>
<body>
<div id="content"></div>
<template id="itemTemplate">
foo
<img id='imageTag' src='image.png'>
</template>
<script>
var templ = document.querySelector('#itemTemplate');
templ.content.querySelector('#imageTag').click = function(){alert('xxxx');};
var content = document.querySelector('#content');
content.appendChild(templ.content.cloneNode(true));
</script>
</body>

Came across the same problem myself, and I will write what I have learned so others will have an answer as well.
As adenine commented, it's impossible to do it from inside the template. I tried that as well. What you could do, is complete the template creation, and when all the elements are registered in the DOM, you could add event listeners then.
So your code will look like:
<!doctype html>
<body>
<div id="content"></div>
<template id="itemTemplate">
foo
<img id='imageTag' src='image.png'>
</template>
<script>
var templ = document.querySelector('#itemTemplate');
var content = document.querySelector('#content');
content.appendChild(templ.content.cloneNode(true));
document.querySelector('#imageTag').click = function(){alert('xxxx');};
</script>
I used to have the same problem when I needed to add event listeners to an array of elements (trying to dynamically build a paginator), so I have used a forEach loop to give each element its click event:
for (var i = 0 ; i < totalPages ; i++) {
anchorElement.innerHTML = i + 1;
anchorElement.dataset.pageId = i + 1;
var clone = document.importNode(templateElement.content, true);
paginationContainer.appendChild(clone);
}
// Register pagination event listeners
document.querySelectorAll('.pagination a').forEach(function(anchorElement) {
$(anchorElement).on('click', function() {
alert('Hello');
});
});

Related

Move the dynamically created buttons in clockwise using JavaScript

I have some input type=button which are created dynamically using JavaScript. Here I need to shift those clockwise while click on button. Here is my code:
<!-- Enter your HTML code here -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Buttons Grid</title>
</head>
<body>
<div id="btns" style="width:75%;">
</div>
<script>
for(var i=0;i<9;i++){
var index=i+1;
var element = document.createElement("input");
element.type = "button";
element.value = index;
element.id = "btn"+index;
element.setAttribute("style","width:30%;height:48px;font-size:24px");
var foo = document.getElementById("btns");
//Append the element in page (in span).
foo.appendChild(element);
}
document.getElementById("btn5").onclick=function(){
}
</script>
</body>
</html>
Here I need when user will click one button 5 the buttons present around button5 will move clockwise means button4 will shift to first place without changing its ids.
Something like this?
let container = document.querySelector("#btns");
container.insertBefore(container.lastElementChild, container.firstElementChild);
// or this ?
// container.appendChild(container.firstElementChild);
I suppose you don't need to create the buttons in js. You can create in html code. And just play with innertext of btns. My approach was like this;
btn5.addEventListener('click', () => {
const textofBtn = btn1.innerText;
btn1.innerText = btn4.innerText;
btn4.innerText = btn7.innerText;
btn7.innerText = btn8.innerText;
btn8.innerText = btn9.innerText;
btn9.innerText = btn6.innerText;
btn6.innerText = btn3.innerText;
btn3.innerText = btn2.innerText;
btn2.innerText = textofBtn;
});
but I saw another solution looking like more elegant here is you can check;
let nums=[1,2,3,6,9,8,7,4];
const ids=[1,2,3,6,9,8,7,4];
let btn5=document.getElementById("btn5");
btn5.onclick=function() {
nums.unshift(nums.pop());
for (i=0; i<=7; i++) {
document.getElementById("btn"+ids[i]).innerHTML=nums[i];
}
}
// writed by mark_russellbro1(hackerrank username)

Passing a variable into a DOM function in Javascript

I took this example from w3schools and modify it to this. The code below is not working.
What I intend to do is hide the div with id "demo1". It is not working. What is the problem?
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(div_id)
{
//here the div_id variable seems to unparsable by the DOM event
document.getElementById(div_id).innerHTML = hello;
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<button onclick="myFunction('demo1')">Click me</button>
<div id="demo1"></div>
<div id="demo2"></div>
</body>
</html>
The variable hello is not defined. You were probably looking to set the innerHTML as a String:
function myFunction(div_id) {
document.getElementById(div_id).innerHTML = "hello";
// -----------------------------------------^-----^
}
DEMO: http://jsfiddle.net/uzuKp/1/
Even though you took an example from W3Schools and modified it, I'd suggest binding events separate from the HTML and storing associated data in data-* attributes. In your example, it can be as something like this:
<p>Click the button to trigger a function.</p>
<button data-div-id="demo1">Click me</button>
<button data-div-id="demo2">Click me</button>
<button data-div-id="demo1">Click me</button>
<div id="demo1">demo1</div>
<div id="demo2">demo2</div>
And the JS:
function clickHandler() {
var targetDivId, targetDiv;
targetDivId = this.getAttribute("data-div-id");
targetDiv = document.getElementById(targetDivId);
targetDiv.innerHTML = "Hello" + new Date().getTime();
}
function loadHandler() {
var buttons, i, j, cur;
buttons = document.getElementsByTagName("button");
for (i = 0, j = buttons.length; i < j; i++) {
cur = buttons[i];
cur.onclick = clickHandler;
}
}
window.onload = loadHandler;
DEMO: http://jsfiddle.net/3K4RD/
Although I would also suggest looking at the following article to see different ways to bind events: addEventListener vs onclick
One final suggestion I have is to not set the innerHTML property. You may have a simple example here, but it's usually a better idea to use DOM methods like appendChild (to add a node) and document.createTextNode (to create text that can be appended). Of course, that would require the contents to be cleared out first, something like:
while (targetDiv.firstChild) {
targetDiv.removeChild(targetDiv.firstChild);
}
targetDiv.appendChild(document.createTextNode("Hello"));
DEMO: http://jsfiddle.net/52Kwe/
You could also store the specific string that needs to be set as the innerHTML as a data-* attribute (especially if it differs between buttons).
UPDATE:
Per your recent edit, the style property is a special property, which is actually a special object with style properties that you need to set. So for your example, you have to set the .style.display value, like:
document.getElementById(div_id).style.display = "none";
document.getElementById(div_id).style.display = 'none';
document.getElementById(div_id).style.visibility= 'hidden';

creating a list in html using jQuery append not working

I've been staring at this code for hours now, any input appreciated.
I want to create a list in a HTML file from an array of objects using jquery append, but it justs stays blank.
HTML:
<html>
<head>
<script src="jquery-1.10.0.js"></script>
<script src="test.js"></script>
<title></title>
</head>
<body>
<div id="list">
</div>
<div id="template">
<div class="info">
<a class="url"></a>
</div>
</div>
</body>
</html>
Script:
function update(events) {
var eventList = $('#list');
eventList.empty();
events.forEach(
function(_event) {
var eventsHtml = $('#template .info').clone();
eventsHtml.find('.url').text(_event.title)
.attr('href', _event.url);
eventList.append(eventsHtml);
});
}
var events = [{title:'fu',url:'bar'}, {title:'bar',url:'fu'}];
update(events);
Assuming the JS code you show is contained in test.js, either move this line:
<script src="test.js"></script>
...to the end of the body (just before the closing </body> tag), or wrap your code in a $(document).ready() handler.
The way you currently have it, this line:
var eventList = $('#list')
...doesn't find the '#list' element because the script runs before the element is parsed. Same problem with finding '#template .info'.
You could wrap all of the code in a ready handler, or if you need to be able to call the update() function from elsewhere just wrap the initial call:
$(document).ready(function() {
var events = [{title:'fu',url:'bar'}, {title:'bar',url:'fu'}];
update(events);
});
Use the following JS code:
$(document).ready(function(){
var events = [{title:'fu',url:'bar'}, {title:'bar',url:'fu'}];
var eventList = $('#list');
eventList.empty();
events.forEach(
function(_event) {
var eventsHtml = $('#template .info').clone();
eventsHtml.find('.url').text(_event.title)
.attr('href', _event.url);
eventList.append(eventsHtml);
});
});

javascript document.getElementById not working

Following is my javascript program. I am trying to get all child tags of parent div tag but when I am running the program document.getElementById('abc') returning null.
function init(){
// currentDiv = document.getElementById("intro");
alert("working");
count = 0;
divs = document.getElementById('abc').getElementsByTagName("div");
alert("HI " + divs)
currentDiv = divs[count];
nextDiv = divs[count + 1]
count = count + 1;
}
window.onload = init();
Following is my div tag definitions:
<div id='abc'>
<div></div>
</div>
thanks.
The problem is in this line:
window.onload = init();
You are running init and setting the return value as the value of window.onload. My guess is that the code is being executed before the DOM is ready, i.e. before the divs exist.
Try this instead:
window.onload = init;
I suggest you start using jQuery instead, then you have much more powerful tools for this kind of DOM search/traversing
<body onload="init()">
<div id='abc'>
<div></div>
</div>
</body>
this probably solves your problem

Javascript Onclicks not working?

I have a jQuery application which finds a specific div, and edit's its inner HTML. As it does this, it adds several divs with onclicks designed to call a function in my JS.
For some strange reason, clicking on these never works if I have a function defined in my code set to activate. However, it works fine when calling "alert("Testing");".
I am quite bewildered at this as I have in the past been able to make code-generated onclicks work just fine. The only thing new here is jQuery.
Code:
function button(votefor)
{
var oc = 'function(){activate();}'
return '<span onclick=\''+oc+'\' class="geoBut">'+ votefor +'</span>';
}
Elsewhere in code:
var buttons = '';
for (var i = 2; i < strs.length; i++)
{
buttons += button(strs[i]);
}
var output = '<div name="pwermess" class="geoCon"><div class="geoBox" style=""><br/><div>'+text+'</div><br/><div>'+buttons+'</div><br/><div name="percentages"></div</div><br/></div>';
$(obj).html(output);
Elsewhere:
function activate()
{
alert("Testing");
}
You may want to take a look at jQuery.live(eventType, eventHandler), which binds an event handler to objects (matching a selector) whenever they are created, e.g.:
$(".somebtn").live("click", myClickHandler);
Follows a dummy example, may be this can help you.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="http://cdn.jquerytools.org/1.2.5/jquery.tools.min.js"></script>
<script type="text/javascript">
$(function() {
$('.go-right').click(function(){
c="Hello world";
$("#output").html(c);
});
});
</script>
</head>
<body >
<div id="output"></div>
<a class="go-right">RIGHT</a>
</body>
</html>
Change this:
var oc = 'function(){activate();}'
To be this instead:
var oc = 'activate();'

Categories

Resources