pass click event between two page by localStorage - javascript

I want to take a click event from 2nd page . 1st page have a link for 2nd page, there have a button when click the button it add a HTML row on 1st page. I am trying to use localStorage for passing data. My code don't work, take a look below:
1st Page.html
HTML
<div id="content">
</div>
JS
var output = document.getElementById('content');
addEvent(window, 'storage', function (event) {
if (event.key == 'StorageName') {
output.innerHTML = event.newValue;
}
});
2nd Page.html
HTML
<input id="data" type="button" value="+" onclick="addRow()">
JS
addEvent(dataInput, 'keyup', function () {
localStorage.setItem('StorageName', this.value);
});
var dataInput = dataInput = document.getElementById('data');
object.onclick = function(){
addRow() {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<button>GO</button>';
document.getElementById('content').appendChild(div);
}
};

You haven't defined your addRow() function properly. A function's name is defined with the keyword function, not inside of the function body. Your code:
object.onclick = function(){
addRow() {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<button>GO</button>';
document.getElementById('content').appendChild(div);
}
};
Should be changed to:
function addRow() {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<button>GO</button>';
document.getElementById('content').appendChild(div);
}
object.onclick = addRow;

I agree with skyline3000's answer the addRow() should be defined. Also there are a few other things that could/should change:
define dataInput before attaching an event to it
object.onclick should be dataInput.onclick since thats the element being clicked. (is click event what you really want? maybe onkeyup?)
when you set the localStorage you want to set the function definition being passed to Page 1 which appears to be addRow(). Simply remove the parenthesis to pass just the definition.(Should also be defined before using)
If you want to just pass the function you shouldn't set the onclick event on Page 2. What you should probably do is record how many times you want it to run when you go to Page 1.
You dont need to pass the function everytime if it isnt changing; Just set it once and record the number of times it was clicked.
page 1 can catch the load event and the check localStorage for the function definition and number of times it was run. Then it can loop and perform the function.
the code you have doesn't add a link back to page 2 if thats what you are looking for but you can add that into the addrow function when you know the file name and path.
Page 1
var output = document.getElementById('content');
addEvent(window, 'load', function (event) {
if (localStorage.getItem('StorageName') && localStorage.getItem('rowsToAdd')) {
for(var i = 0; i > rowsToAdd;i++){
var addNewRow = localStorage.getItem('StorageName');
addNewRow();
}
}
});
Page 2
var dataInput = document.getElementById('data');
function addRow() {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<button>GO</button>';
document.getElementById('content').appendChild(div);
};
localStorage.setItem('StorageName', addRow);
dataInput.onclick = function() {
if(localStorage.getItem('rowsToAdd')){
localStorage.setItem('rowsToAdd', localStorage.getItem('rowsToAdd') + 1);
}else{
localStorage.setItem('rowsToAdd',1);
}
}
I didn't test this code so it may not work copy+pasted but something pretty close hopefully.
I also answered this with the best understanding of what you wanted that I could manage but I dont fully see the desired result of what you seemed to be doing.

Related

Button Doesn't Work If Created Using innerHTML

I have this kind of structure
<button ng-click="something(1)">click!</button>
<div id="place"></div>
something() works in this situation, but if I try to make another button with innerHTML on a js code
str="<button ng-click=\"something(2)\">click 2!</button>"
document.getElementById("place").innerHTML = str;
thrn the 2nd button, the one created by innerHTML, apears normal, but doesn't call the function something() when clicked
Is there a nother way to add the button? the buttons should be generated proceduraly as the page runs
Thank you very much!
<script>
let btn = document.createElement("button");
btn.innerText = "click2"
// class
btn.classList = [];
// on click function
btn.onclick = () => {
}
document.getElementById("place").innerHTML = "";
document.getElementById("place").appendChild(btn)
</script>

I have a problem with an id in onClick event JavaScript function

I am trying to make a little idle click game, but have a problem with my startIdle function.
I can't pass the id to which input progressbar that is needed to start counting.
I have one input field and one button foreach id from a obj.
function addRow(id) {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML =
'<div class="w3-blue" name="idle" id="'+id+'" style="height:24px;width:20%"></div>\
<button onclick="startIdle('+id+')">Click me</button>';
document.getElementById('content').appendChild(div);
}
function startIdle(id) {
_counter = 1;
_timer = setInterval(function(){
document.getElementById(id).style.width = (_counter + "%");
_counter++;
if(_counter > 100) clearInterval(_timer);
}, 100);
}
function createIdles(){
for (var key in money) {
// skip loop if the property is from prototype
if (!money.hasOwnProperty(key)) continue;
var obj = money[key].id;
addRow(obj)
}
}
createIdles()
this is the console.log I get:
Uncaught ReferenceError: startIdle is not defined at HTMLButtonElement.onclick
Your problem is that startIdle is defined inside a scope. Move it out of document.ready. Unless you can call the function from console, it isn't available globally.
Alternatively, building on Andy Hoffmans solution, bind onClick programmatically inside scope of document.ready, e.g.
document.querySelectorAll('button[data-id]')
.forEach(elm => elm.addEventListener('click',
() => startIdle(elm.dataset.id)))
You can probably improve that a bit using jquery.
I removed the onclick attribute and perform binding separately. The binding and element lookup are done inside of a setTimeout to ensure the elements are present in the DOM when that code runs.
// Note: I'm using a data-id attribute on the <button> so as to not
// duplicate the id on the <div class="w-3">
function addRow(id) {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML =
'<div class="w3-blue" name="idle" id="' + id + '" style="height:24px;width:20%"></div>\
<button data-id="' + id + '">Click me</button>';
document.getElementById('content').appendChild(div);
}
function startIdle() {
// Remember the data-id attribute from above?
alert('clicked ' + this.getAttribute('data-id'));
}
for (var i = 0; i < 5; i++) {
addRow(i);
}
// Bind click events in separate event loop to ensure elements are present in DOM
setTimeout(function() {
var els = document.querySelectorAll("button[data-id]");
els.forEach(function(el) {
el.addEventListener("click", startIdle);
})
});
<div id="content"></div>
http://jsfiddle.net/4mr02ktu/2/

onclick() automatic firing on loading but failing afterwards

I understand that onclick() in html with parenthesis calls automatically. But in my situation, I want to pass a parameter into the onclick function(specifically, the element clicked). So how do I manage this without having onclick fired when the page loads? In addition, the onclick method does not fire after its automatically firing upon loading. My code is below:
for (i = 0; i < returnPostPhotoSrcs().length; i++) {
// var photosArray=returnPhotoNames()
// var imgName=photosArray[i]
var imgSrcArray=returnPostPhotoSrcs();
var imgSrc=imgSrcArray[i]
var postNamesArray=returnPostNamesArray();
var postName=returnPostNamesArray[i]
var img=img_create(imgSrc,postName,'')
img.style.width=returnPostHeight();
img.style.height=returnPostWidth();
img.className="postImage";
img.onmousedown=playShout(img);
var postNamesArray=returnPostNames();
var innerSpan = document.createElement('span');
innerSpan.onmousedown=playShout(innerSpan); //problem line
var text = postNamesArray[i];
innerSpan.innerHTML = text; // clear existing, dont actually know what this does
var outerSpan = document.createElement('span');
outerSpan.className="text-content";
outerSpan.onmousedown=playShout(outerSpan); //another problem line, also doesnt call onclick
var li = document.createElement('li');
var imgSpacer=img_create('spacerSource',"spacer",'')
imgSpacer.style.width="25px";
imgSpacer.style.height=returnPostWidth();
li.appendChild(img)
outerSpan.appendChild(innerSpan)
li.appendChild(imgSpacer)
imgSpacer.style.opacity="0"
// if (i>0 && i<returnPostPhotoSrcs().length-1) {
// hackey
var imgSpacer=img_create('spacerSource',"spacer",'')
imgSpacer.style.width="25px";
imgSpacer.style.height=returnPostWidth();
li.appendChild(imgSpacer)
li.appendChild(outerSpan)
imgSpacer.style.opacity="0"
// }
var outerDiv = document.getElementById("postDivOuter");
outerDiv.appendChild(li)
}
Adding onto this you could also do:
img.onmousedown= function(e) { playShout(e) };
//for playshout
playshout = function(e) {
var element = e.target; //this contains the element that was clicked
};
The function fires because you are calling it. You need to use a closure
img.onmousedown= function() { playShout(img) };
As others have shown, you can create an anonymous function, or another option is to use .bind():
innerSpan.onmousedown = playShout.bind(null, innerSpan);

Click event object tracking woes

So I am working on this but of jQuery that gets the element id through a click event. This then triggers a function that acts like the deprecated .toggle()- it slides an element down on the fist click and slides that element up on the second click. However, there is a bug that causes the element to slide up and down the amount of times that it has been clicked on. For instance, if this is the second time I use the .clickToggle function, the element (table) slides up and down twice before settling, and so on. I suspect it has something to do with the event object, e, tracking the number of clicks-- i.e. I probably shouldn't set id = e.target.id-- but I'm not sure how to fix while still getting the relevant element id that I need.
Here is the relevant clickToggle plug in (courtesy of an answer here on stackoverflow).
(function($) {
$.fn.clickToggle = function(func1, func2) {
var funcs = [func1, func2];
this.data('toggleclicked', 0);
this.click(function() {
var data = $(this).data();
var tc = data.toggleclicked;
$.proxy(funcs[tc], this)();
data.toggleclicked = (tc + 1) % 2;
});
return this;
};
}(jQuery));
Here is the buggy code that fits the above description.
$(document).click(function(e) {
//get the mouse info, and parse out the relevant generated div num
var id = e.target.id;
var strId = id.match(/\d$/);
//clickToggle the individual table
$('#showTable' + strId).clickToggle(function () {
$('#table' + strId).slideDown();
$('#table' + strId).load('files.php');
},
function () {
$('#table' + strId).slideUp();
});
});//close mousemove function
Any help would be much appreciated. Thanks.
The problem is that you're registering a new click handler for the element each time you invoke clickToggle:
this.click(function() {...
On each subsequent click, you add another handler, as well as invoking all previous handlers. Bleagh.
Better to be straightforward: (DEMO)
var showTable = function($table) {
$table.slideDown();
$table.load('files.php');
$table.removeClass('hidden');
};
var hideTable = function($table) {
$table.slideUp();
$table.addClass('hidden');
};
$(document).click(function (e) {
//get the mouse info, and parse out the relevant generated div num
var id = e.target.id;
var strId = id.match(/\d$/)[0];
var $table = $('#table' + strId);
if ($table.hasClass('hidden')) {
showTable($table);
} else {
hideTable($table);
}
});

How to add onclick event to exist element by Javascript? (document.getElementbyID)

I have a button in my project that when you click over it a function call and add onclick event to all certain elements in my project and show my hidden popup element container.
I have a function that search all exist element in my page and add onclick event to some of elements that they have certain class.
My element is stored in a list array. in each cell of this array (array name is list) stored an element like below:
list[0] = document.getElementById("my_div_id");
list[1] = document.getElementById("my_div_id_1");
list[2] = document.getElementById("my_div_id_2");
...
list[n] = document.getElementById("my_div_id_n");
and I have a function like below in top of my Javascript code:
function say_hello(e, msg) {
if (e == null) e = window.event;
//now e handler mouse event in all browser !!!
alert (e + "::" + msg);
}
I have a function to add onclick event to each element in array. I add onclick event in type of below (separated with (*) comment) but doesn't work any of them:
function search_and_add_events_to_all_dragable_elements (list) {
for (var z = 0; z < list.length; z++) {
list[z].href = "javascript:;";
var e;
var test_msg = "VAYYYYYYYYYY";
/**************
element.onclick = new Function { alert ('hi'); };
element.onclick = new Function () { alert ('hi'); };
element.onclick = new function { alert ('hi'); };
element.onclick = new function () { alert ('hi'); };
element.onclick = new function () { return alert ('hi'); };
element.onclick = function () { return alert ('hi'); };
element.onclick = alert ('hi');
element.onclick = "alert ('hi');";
element.onclick = say_hello(e, test_msg);
element.onclick = "say_hello();";
element.onclick = (function (e, test_msg) { return function(e) { sib(e, test_msg); };
element.onclick = (function () { return function() { alert("ahaaay"); };
**************/
list[z].style["padding"] = "20px";
list[z].style["border"] = "solid 10px";
list[z].style["backgroundColor"] = "#CCC";
}
}
I change style in end of my code to perform my code is work and end truly. style change every time but onclick event doesn't add to my div.
only one way add onclick to my project. that is same as below:
list[z].setAttribute("onclick", "alert(\"hi\");");
but are there better ways?
There is a better way. My first mistake was using JavaScript before my all element load on my page. to solve it you must call element in end of page load or put your javascript code in end of your project. then your code execute exactly when your elements are exist in your page.
for more details about it see links below:
JavaScript that executes after page load
http://www.w3schools.com/jsref/event_onload.asp
My second mistake was hurt :(
I has a div that hold all of my other elements in itself. it was styled display: none; on load. when I call my function it was displayed none and all thins work well (like my new styling) but onclick event didn't work :(( and I spent two days to solve this :((
only be careful your element should not be display: none styled when you are adding your onclick event to it.
then you can use this type of creation onclick event dynamically to your project:
list[z].onclick = (function (e, test_msg) {
return function(e) {
sib(e, test_msg);
};
})(e, test_msg);
this is best way that I know. you can manage event handler and send your arguments also to your function.
I use several time another way of dynamically add onclick event in my project.

Categories

Resources