div not firing onclick event in javascript - javascript

my div element is :
<div id="div"></div>
below is javascript.:
function makediv() {
var divmy = document.getElementById("div");
var row ='';
var color='#ccc';
for(var i=0;i<2;i++)
{
divmy.innerHTML += " <div class='dynamic' id='inner"+i+"' onclick=searchFilterations(i)>"+i+"</div> ";
color='black';
}
}
function searchFilterations(e){
alert(e);
}
problem is: searchFilterations() function not firing on click.what is the error?
here is fiddle :
http://jsfiddle.net/cjT4s/4/

Please call makediv function onload event
window.onload = makediv;
function makediv() {
var divmy = document.getElementById("div");
var row ='';
var color='#ccc';
for(var i=0;i<2;i++)
{
// divmy.innerHTML += " <div style='width: 100px;height: 30px;background-color:"+color+" ;' onclick=javascript:alert("+i+")></div> ";
divmy.innerHTML += " <div class='dynamic' id='inner"+i+"' onclick=searchFilteration("+i+")>"+i+"</div> ";
color='black';
}
}
function searchFilteration(i){
alert(i);
}
FIDDLE DEMO

Try this with window.searchFilteration = function (i) { ... }:
makediv();
function makediv() {
var divmy = document.getElementById("div");
var row ='';
var color='#ccc';
for(var i=0;i<2;i++)
{
divmy.innerHTML += " <div class='dynamic' id='inner"+i+"' onclick='searchFilteration("+i+")'>"+i+"</div> ";
color='black';
}
}
window.searchFilteration = function (i){
alert(i);
}
FIDDLE DEMO

Related

javascript check onchange function on dynamic element

I created an HTML array with some tr lines which need to be hidden by default and when user check the checkbox, the element is showed.
I have a Javascript function to show html element when checkbox is checked. It works but not when I use a loop.
I need that checkbox1 works on tr1, checkbox2 on tr2 ...
The PHP code which creates elements
<?php
if (isset($_SESSION['wordsListArray']))
{
$length = count($_SESSION['wordsListArray']);
for ($i = 0; $i < $length; $i++)
{
echo '<tr><td>' . htmlspecialchars($_SESSION['wordsListArray'][$i]) . '</td><td>' . htmlspecialchars($_SESSION['translationsListArray'][$i]) . '</td><td><input type="checkbox" id="checkboxId' . ($i+1) . '"/></td></tr>';
echo '<tr class="trHide" id="trHide' . ($i+1) . '"><td><input type="text" placeholder=' . $_SESSION['personel_language_array'][0] . '></td><td><input type="text" name="other" placeholder=' . $_SESSION['personel_language_array'][1] . '></td><td><button type="submit">Edit</button><button type="submit">Erase</button></td></tr>';
}
}
?>
This Javascript works but only on one element (getElementById is unique), but I need a loop to use different Id (trHide1, trHide2 ...)
var tr = document.getElementById("trHide1");
var check = document.getElementById("checkboxId1");
check.onchange = function() {
if(check.checked)
{
tr.style.display = 'contents';
}
else
{
tr.style.display = 'none';
}
};
I try this loop but it doesn't work.
for (var i = 1; i <= lengthWordList; i++)
{
var trId = 'trHide' + i;
var checkId = 'checkboxId' + i;
var tr = document.getElementById(trId);
var check = document.getElementById(checkId);
check.onchange = function() {
if(check.checked)
{
tr.style.display = 'contents';
}
else
{
tr.style.display = 'none';
}
};
}
Your code does not work because it overwrites the event and the selector
This could be worth it
var elemento=[];
for (var i = 1; i <= 2; i++)
{
var trId = 'trHide' + i;
var checkId = 'checkboxId' + i;
console.log(trId);
elemento.push(
{
tr:document.getElementById(trId),
check:document.getElementById(checkId),
event:function(){}
}
);
console.log(elemento[(i-1)]);
elemento[(i-1)].check.setAttribute('elemento',(i-1));
elemento[(i-1)].event = elemento[(i-1)].check.onchange = function() {
var valor = this.getAttribute('elemento');
if(elemento[valor].check.checked)
{
elemento[valor].tr.style.display = 'contents';
}
else
{
elemento[valor].tr.style.display = 'none';
}
};
}
var elemento=[];
for (var i = 1; i <= 2; i++)
{
var trId = 'trHide' + i;
var checkId = 'checkboxId' + i;
console.log(trId);
elemento.push(
{
tr:document.getElementById(trId),
check:document.getElementById(checkId),
event:function(){}
}
);
console.log(elemento[(i-1)]);
elemento[(i-1)].check.setAttribute('elemento',(i-1));
elemento[(i-1)].event = elemento[(i-1)].check.onchange = function() {
var valor = this.getAttribute('elemento');
if(elemento[valor].check.checked)
{
elemento[valor].tr.style.display = 'contents';
}
else
{
elemento[valor].tr.style.display = 'none';
}
};
}
<table>
<tr id="trHide1" style="display:none"><td>AAAA</td></tr>
<tr id="trHide2" style="display:none"><td>BBBB</td></tr>
</table>
<input type="checkbox" id="checkboxId1">
<input type="checkbox" id="checkboxId2">

how do i add functionality to each of the buttons?

The first part of the code is working correctly, but now that each button appears, how do i add functionality to each of them? currently the only button which does something when pressed is always the last one, the rest do nothing.
Change it to
{
var output = "";
var data = JSON.parse(e.target.responseText);
for(var i=0; i<data.length; i++)
{
output = data[i].title + ' ';
var p = document.createElement("p");
var div = document.getElementById("response");
var textNode = document.createTextNode(output);
p.appendChild(textNode);
var button = document.createElement("button");
button.innerHTML = "Download";
p.appendChild(button);
div.appendChild(p);
button.addEventListener ("click", () =>
{
alert("Test");
});
}
}
You are adding the below code out side the for loop
button.addEventListener ("click", () =>
{
alert("Test");
} );
Keep the above code inside the for loop. So that for each button the event listener will be added.
Another way to approach this would be to add the callback function to the onclick variable of the elements prototype:
function doStuff() {
var output = "";
var data = JSON.parse(e.target.responseText);
for (var i = 0; i < data.length; i++) {
output = data[i].title + ' ';
var p = document.createElement("p");
var div = document.getElementById("response");
var textNode = document.createTextNode(output);
p.appendChild(textNode);
var button = document.createElement("button");
button.innerHTML = "Download";
// Adds the callback function here
button.onclick = () => {
// fill in your arrow function here...
alert("Test");
};
p.appendChild(button);
div.appendChild(p);
};
}
doStuff();
Here is a jsFiddle
You should use event delegation for dynamically added elements
// sample data
var data = [{
title: 'one'
}, {
title: 'two'
},{
title: 'three'
}];
var output = "";
for (var i = 0; i < data.length; i++) {
var output = data[i].title + " ";
var p = document.createElement("p");
var div = document.getElementById("response");
var textNode = document.createTextNode(output);
p.appendChild(textNode);
var button = document.createElement("button");
// added output to button text for identification
button.innerHTML = output + " Download";
p.appendChild(button);
div.appendChild(p);
}
// Get the parent element, add a click listener
document.getElementById("response").addEventListener("click", function(e) {
// e.target is the clicked element!
// If it was a button
if (e.target && e.target.nodeName == "BUTTON") {
// Button found! Output the identifying data!
// do other work on click
document.getElementById("display").innerHTML = e.target.innerHTML + " Clicked";
}
});
<div id="response"></div>
<div id="display">Display</div>

Jquery UI Sortable not working in Dynamic container

I have a container where I dynamically add sections, I create items inside the section , that should be sortable, But Jquery sortable does not work inside dynamically created containers, while if I give the containers static it works,
Can anyone please share a solution.Thanks
https://jsfiddle.net/anubala/7ut5wk3j/1/
HTML:
<div class='row page-layout'>
<div class='col-md-10 col-md-offset-1' >
<div class="add_section_div">
<p>Add section</p>
</div>
<div id="contents">
</div>
</div>
</div>
JavaScript:
$(".wrap_body").sortable();
$(".add_section_div").on("click", function() {
var $section = "<div class='section_div'><div class='div_header clearfix'><p class='pull-left'>Add Wrap</p></div><div class='section_body div_body'></div></div>";
$("#contents").append($section);
})
$("body").on("click", ".section_div>.div_header", function() {
var $wrap = "<div class='wrap_div'><div class='div_header clearfix'><p class='pull-left'>Add Item</p></div><div class='wrap_body div_body clearfix'></div></div>";
$(this).parent().find('.section_body').append($wrap);
})
const regex = /^.*-\s*(.*)$/;
$("body").on("click", ".wrap_div>.div_header", function() {
var $item1 = "<div class='drag col-sm-";
var $item2 = "'><div class='item_div'><div class='div_header clearfix'><p class='pull-left'><span class='minus'><i class='fa fa-minus'></i></span><span class='plus'><i class='fa fa-plus'></i></span></p><p class='pull-left header_text'>";
var $item3 = "</p></div><div class='div_body'></div></div></div>";
var length_item = $(this).parent().find(".wrap_body .item_div").length;
var count = 0;
for (i = 0; i < length_item; i++) {
if ($(this).parent().find(".wrap_body>div:eq('" + i + "')")) {
console.log($(this).parent().find(".wrap_body>div:eq('" + i + "')"))
var col_count_text = $(this).parent().find(".wrap_body>div:eq('" + i + "')").attr('class');
count += parseInt(find_col_count(col_count_text));
}
}
var current_col_count = 12 - (count % 12);
if (count < 12) {
$(this).parent().find('.wrap_body').append($item1 + current_col_count + $item2 + "col-sm-" + current_col_count + $item3);
}
})
function find_col_count(col_text) {
var col_count = regex.exec(col_text);
col_count.forEach((match, groupIndex) => {
count1 = match;
});
return count1;
}
$("body").on("click", ".plus", function() {
var $parent = $(this).parent().parent().parent().parent();
var col_count_text = $parent.attr('class');
var length_item = $parent.parent().find(".item_div").length;
var count = 0;
for (i = 0; i < length_item; i++) {
if ($parent.parent().find(".item_div:eq('" + i + "')").parent()) {
var col_count_text = $parent.parent().find(".item_div:eq('" + i + "')").parent().attr('class');
count += parseInt(find_col_count(col_count_text));
}
}
var col_count_text = $parent.attr('class');
var col_count = find_col_count(col_count_text);
if (count < 12) {
var col_count_new = "col-sm-" + (++col_count);
var col_count_drag = "drag " + col_count_new;
$parent.attr("class", col_count_drag);
$parent.find(".header_text").html(col_count_new);
}
});
$("body").on("click", ".minus", function() {
var $parent = $(this).parent().parent().parent().parent();
var col_count_text = $parent.attr('class');
var col_count = find_col_count(col_count_text);
if (col_count > 1) {
var col_count_new = "col-sm-" + (--col_count);
var col_count_drag = "drag " + col_count_new;
$parent.attr("class", col_count_drag);
$parent.find(".header_text").html(col_count_new);
}
});
You probably may have found the solution already but to solve this issue you only need to move this line
$(".wrap_body").sortable();
To where you actually append the .wrapper_body to the body as following:
$("body").on("click", ".section_div>.div_header", function() {
var $wrap = "<div class='wrap_div'><div class='div_header clearfix'><p class='pull-left'>Add Item</p></div><div class='wrap_body div_body clearfix'></div></div>";
$(this).parent().find('.section_body').append($wrap);
$(".wrap_body").sortable();
});
This should solve your problem. See JsFiddle

Change div background on click and on mouse over

I am trying to change picture in div on mouse over and on click using JS. Like that:
var favs = document.getElementsByClassName("fav-wrapper");
for (var i = 0; i < favs.length; i++) {
favs[i].innerHTML = '<img src="images/favorite.png" />';
favs[i].onMouseOver = function () {
favs[i].innerHTML = "<img src='images/favorite_hover.png' />";
}
favs[i].onClick = function () {
favs[i].innerHTML = "<img src='images/favorite_on.png' />";
};
}
But for some reason it won't work. What am I doing wrong?
Try lowercase event handlers and actually you need a closure to have the [i] work inside the loop. I prefer using this in your case.
var favs = document.getElementsByClassName("fav-wrapper");
for (var i = 0; i < favs.length; i++) {
favs[i].innerHTML = '<img src="images/favorite.png" />';
favs[i].onmouseover = function () {
this.innerHTML = "<img src='images/favorite_hover.png' />";
}
favs[i].onclick = function () {
this.innerHTML = "<img src='images/favorite_on.png' />";
}
}
but why not just change the src of the images?
var favs = document.getElementsByClassName("fav-wrapper");
for (var i = 0; i < favs.length; i++) {
var fav=favs[i];
fav.getElementsByTagName("img")[0].src="images/favorite.png";
fav.onmouseover = function () {
this.getElementsByTagName("img")[0].src="images/favorite_hover.png";
}
fav.onmouseout = function () {
this.getElementsByTagName("img")[0].src="images/favorite.png";
}
fav.onclick = function () {
this.getElementsByTagName("img")[0].src="images/favorite_on.png";
}
}
you could do all this with CSS by the way
you can try this method using pure css changing background on hover and on click
.image{width:500px;height:500px;background-image: url("http://www.toolsformoney.com/financial_software_demos.jpg");background-repeat: no-repeat;}
.image:hover{background-image: url("http://www.hostpph.com/blog/wp-content/uploads/2012/06/free-bookie-software-demo-large.jpg");background-repeat: no-repeat;}
.image:focus{background-image: url("https://www.arxan.com/wp-content/uploads/assets1/images/demo.png");background-repeat: no-repeat;outline: 0;transition:0s;}
<div class="image" tabindex="0">
</div>

Print every loop, not just the final answer

I want the program to print change the innerHTML of th id "resposta" every time a loop runs. But its just changing the value when the loop ends. I want the page to change the content of the div every second.
I have this code:
<script>
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
function escrever(){
for (i = 0; i < 10; i++) {
var resp = "Executando " + i;
document.getElementById("resposta").innerHTML = resp;
sleep(1000);
}
document.getElementById("resposta").innerHTML += "<br> fim";
}
</script>
Best to use setInterval/setTimeout to delay an execution of a function instead of for loops
function escrever(count){
var ele = document.getElementById("resposta");
if(count > 10){
ele.innerHTML += "<br> fim";
return;
}
ele.innerHTML = "Executando " + count;
setTimeout(escrever.bind(null,++count),1000);
}
escrever(1);
<div id="resposta"></div>
Better to use setInterval like bellow
var i = 0;
var interval = setInterval(function(){
var resp = "Executando " + i++;
document.getElementById("resposta").innerHTML = resp;
if(i>=10){
document.getElementById("resposta").innerHTML += "<br> fim";
clearInterval(interval);
}
},1000);
DEMO
<script>
$(document).ready(function(){
var count=0;
interval = setInterval(function() {
if(count<10){
$("#resposta").html('test'+count);
} else {
clearInterval(interval);
}
count ++;
},1000);
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="resposta"></div>
You can use setTimeout():
var timeout;
function sleepME(i){
if(i <= 10){
timeout = setTimeout((function(){
var resp = "Executando " + i;
document.getElementById("resposta").innerHTML = resp;
sleepME(++i);
}), 1000);
} else {
document.getElementById("resposta").innerHTML += "<br> fim";
clearTimeout(timeout);
}
}
sleepME(1);
<div id="resposta"></div>

Categories