onclick() automatic firing on loading but failing afterwards - javascript

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);

Related

pass click event between two page by localStorage

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.

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);
}
});

Copy/Paste element with jQuery

I have a div that I'm appending to another div when a button is clicked. I'm also calling a bunch of functions on the div that gets created.
HTML
<a onClick="drawRect();">Rect</a>
JS
function drawRect(){
var elemRect = document.createElement('div');
elemRect.className = 'elem elemRect';
elemRect.style.position = "absolute";
elemRect.style.background = "#ecf0f1";
elemRect.style.width = "100%";
elemRect.style.height = "100%";
elemRect.style.opacity = "100";
renderUIObject(elemRect);
$('.elemContainer').draggableParent();
$('.elemContainer').resizableParent();
makeDeselectable();
handleDblClick();
}
var createDefaultElement = function() {
..
..
};
var handleDblClick = function() {
..
..
};
var renderUIObject = function(object) {
..
..
};
var makeDeselectable = function() {
..
..
};
I could clone the element when the browser detects a keydown event
$(window).keydown(function(e) {
if (e.keyCode == 77) {
$('.ui-selected').clone();
return false;
}
});
then append it to #canvas. But the problem is, none of the functions I mentioned above get called with this method.
How can I copy/paste an element (by pressing CMD+C then CMD+V) and call those above functions on the cloned element?
The jQuery.clone method returns the cloned node. So you could adjust your code to do something like this:
var myNodes = $('.ui-selected').clone();
myNodes.each(function () {
createDefaultElement(this);
appendResizeHandles(this);
appendOutline(this);
});

How can i optimize my Jquery code?

I've created some JavaScript using Jquery, for the page animation :
I trying to optimize it since i repeat the same thing for subtab1, subtab2, subtab3.
The same function is executed for all of them, and the only thing is changes is variable i iterating on?
Any suggestion?
<script type="text/javascript">
$(document).ready(function () {
var $defensivo = $('#defensivoimg');
var $equilibrado = $('#equilibradoimg');
var $activo = $('#activoimg');
var $defensivoSubTab = $('#subtab1');
var $equilibradoSubTab = $('#subtab2');
var $activoSubTab = $('#subtab3');
var $fundosdiponiveis = $('#fundosdiponiveis');
var $fundosdiponiveisTab = $('#tabs1');
$defensivo.live('click', function () {
$fundosdiponiveis.removeClass("subshow show").addClass("hide");
$defensivoSubTab.removeClass("hide");
$defensivoSubTab.show();
});
$equilibrado.live('click', function () {
$fundosdiponiveis.removeClass("subshow show").addClass("hide");
$equilibradoSubTab.removeClass("hide");
$equilibradoSubTab.show();
});
$activo.live('click', function () {
$fundosdiponiveis.removeClass("subshow show").addClass("hide");
$activoSubTab.removeClass("hide");
$activoSubTab.show();
});
});
</script>
For a while:
var $fundosdiponiveis = $('#fundosdiponiveis');
This is my default div.
var $defensivoSubTab = $('#subtab1');
var $equilibradoSubTab = $('#subtab2');
var $activoSubTab = $('#subtab3');
That divs apears when i clicking on one of the following tabs:
var $defensivo = $('#defensivoimg');
var $equilibrado = $('#equilibradoimg');
var $activo = $('#activoimg');
And that button hides and changes style"display" to none, on click, of my three #subtab's
var $fundosdiponiveisTab = $('#tabs1');
Any suggestion?
You could write a function that returns the proper function:
function createShowTabFunc(tab) {
return function () {
$fundosdiponiveis.removeClass("subshow show").addClass("hide");
tab.removeClass("hide");
tab.show();
}
}
Then assign your click handlers:
$defensivo.live('click', createShowTabFunc($defensivoSubTab));
$equilibrado.live('click', createShowTabFunc($equilibradoSubTab));
$activo.live('click', createShowTabFunc($activoSubTab));
Have a common class attribute to all the tab's and you just need to write $('.class').click() and in this get the id of the corresponding tab and according to the id fetched by attr function, you can have an if else to define your variables inside the if else and execute your code block.

How to call javascript function only once during window.onscroll event?

function getH4() {
var xyz = document.getElementsByClassName('bucket_left');
for(var i=0;i<xyz.length;i++){
var x=document.getElementsByTagName("h4")[i].innerHTML;
var current_bucket = xyz[i];
var y=current_bucket.firstChild.href;
var newdiv = document.createElement('div');
newdiv.innerHTML = ""+x+"";
newdiv.className = "hover_title_h4";
current_bucket.appendChild(newdiv);
}
}
window.onscroll=getH4;
In above code i want to append new div in set of divs having class bucket_left and this divs generated from infinite scrolling. above code is working fine but on scroll it appends so many divs.
so how do i append only once ?
Add the following line at the end of your function:
function getH4() {
// ...
window.onscroll = null;
}
create a global boolean variable and set it to false. again set it to true in the window scroll event and chk the variable is false using a if block. put your code inside that if block.
var isScrolled = false;
function getH4() {
if(!isScrolled){
//your code
}
isScrolled = true
}
You only have to set the onscroll property to none as following at the end of you JavaScript function:
window.onscroll = null;
Now when the script executes for the first time, it will perform its function and the above line will set the onscroll to null and thus will not invoke any event on scroll of your mouse and so your function wont be invoked again and again on the event except for the first time.
Or you could handle it logically by setting a public var say var check = 0 and then set the variable to 1 when entered for the first time. So you need to check the value of check and based on that execute the function
var check = 1;
function getH4() {
if(check==1)
{
var xyz = document.getElementsByClassName('bucket_left');
for(var i=0;i<xyz.length;i++){
var x=document.getElementsByTagName("h4")[i].innerHTML;
var current_bucket = xyz[i];
var y=current_bucket.firstChild.href;
var newdiv = document.createElement('div');
newdiv.innerHTML = ""+x+"";
newdiv.className = "hover_title_h4";
current_bucket.appendChild(newdiv);
}
check=0;
}
}
you can try this:
when scrolling,the check equal false, and the append event will happen just once;
when the scroll end(mouseup or mouseout), the check equal true, you can append again.
var check = true;
function getH4(event) {
event.target.onmouseup = function() {
check = true;
}
event.target.onmouseout = function() {
check = true;
}
if (check) {
var xyz = document.getElementsByClassName('bucket_left');
for(var i=0;i<xyz.length;i++){
var x=document.getElementsByTagName("h4")[i].innerHTML;
var current_bucket = xyz[i];
var y=current_bucket.firstChild.href;
var newdiv = document.createElement('div');
newdiv.innerHTML = ""+x+"";
newdiv.className = "hover_title_h4";
current_bucket.appendChild(newdiv);
}
check = false;
}
window.onscroll=getH4

Categories

Resources