I need to add a onclick function to multiple canvas in a . I use a for loop to go through all the canvas and then add the onclick event with attachEvent.
I already tried with an eventlistener or directly adding the onclick event but nothing seems to work please let me know if you can see my mistake...
Here's my JavaScript code:
//here's the loop where the canvas get their width, height and onclick
//event.
function canvasSize() {
var canvas=document.getElementsByTagName('canvas');
var ctx;
for (var i=0;i<canvas.length;i++) {
canvas[i].width="50";
canvas[i].height="50";
ctx=canvas[i].getContext('2d');
ctx.fillRect(0,0,50,50);
ctx.fillStyle="blue";
canvas[i].attachEvent("click", onClick(this,"voitures"));
}
};
//onclick() function
function onClick(elem,theme) {
var images=preloadImages(theme);
var canvas=getElementsByTagName("canvas");
for (var i=0;i<canvas.length;i++) {
if (canvas[i]==elem) {
elem.drawImage(images[0],0,0)
}
}
};
//function where I preload every images
function preloadImages(theme) {
var tab=[];
var imageObj= new Image();
if (theme=="cars") {
tab[0]="0.jpg"
tab[1]="1.jpg"
tab[2]="2.jpg"
tab[3]="3.jpg"
tab[4]="4.jpg"
tab[5]="5.jpg"
tab[6]="6.jpg"
tab[7]="7.jpg"
tab[8]="8.jpg"
tab[9]="9.jpg"
tab[10]="10.jpg"
tab[11]="11.jpg"
tab[12]="12.jpg"
//...
}
for (var i=0;i<32;i++) {
imageObj.src=tab[i];
//imageObj.onload=alert("img "+i+" is loaded");
}
return tab;
}
}
The code crash before adding the onclick function. Hope someone can help me find my mistake.
One: attachEvent is only available in IE.
Two: DON'T name functions onClick it's a reserved global event handler.
So to fix your for loop I would change your last line to this:
for (var i=0;i<canvas.length;i++) {
var self = this;
if(window.attachEvent){
canvas[i].attachEvent("click", function(){
newNameForOnClickFunction(self, "voitures");
}, false);
}else{
canvas[i].addEventListener("click", function(){
newNameForOnClickFunction(self, "voitures");
}, false);
}
}
I'm betting that you want to pass the canvis to your next function and not a refrence to your canvasSize function. If that's the case then you should pass canvas[i] instead of this (or self in my example above)
Related
Just don't know why this piece of code is not working: (onClick not working, click() is working (using console))
function click(ID)
{
if(cost[ID] <= currency[costID[ID]])
{
currency[costID[ID]] -= cost[ID];
currency[ID] += buyamout[ID];
document.getElementById(x[costID[ID]]).innerHTML = "<center>"+(Math.round(notyfication(currency[costID[ID]])*100)/100)+not+"</center>";
document.getElementById(x[gainID[ID]]).innerHTML = "<center>"+(Math.round(notyfication(currency[gainID[ID]])*100)/100)+not+"</center>";
}
}
...'<button onClick="click('+i+');">'+button+x[i]+'</button>'
this gives output <button onClick="click(0);">Make DNA</button>
and after clicking button nothing happens.
There could be a namespace conflict with your click. Use another name like button_click below
var i = 0;
var button = "Make ";
var x = [['DNA']]
document.writeln('<button onclick="button_click('+i+');" >'+(button+x[i])+'</button>');
function button_click(ID) { // notice the function name change
alert(ID);
}
Code below not working:
var i = 0;
var button = "Make ";
var x = [['DNA']]
document.writeln('<button onclick="click('+i+');" >'+(button+x[i])+'</button>');
function click(ID) { // the function name click may have been used already
alert(ID);
}
indeed onclick="click('+i+');" executes the javaScript code between the double brackets: click('+i+');: it calls the javaScript click() function, but this does not work if you declare function click() and someone else did that elsewhere in javaScript code.
if onClick is not working you can also use addEventListener will do the same job.
for e.g.
element.addEventListener('click', function() { /* do stuff here*/ }, false);
To answer your question you must do the following.
Change:
onClick="click(0)"
To:
onclick="click(0)"
That will most probably fix your problem.
I have a local page to help in HTML and JavaScript that helps me with some basic tasks at work. I've been going back over my code and rewriting it to use best practices, since it helps me learn, and recently I've been trying to study namespacing and put it to use by rewriting the common page functions and event listeners.
window.onload = (function() {
var automationPageWrapper = (function() {
var self = {}
self.evntListeners = {
btnTextChange: function() {
// Code that changes button text when clicked
},
btnColorChange: function(formID) {
// Code that iterates through buttons with a certain name
// and makes them all the same default color
}
}
self.listeners = {
btnListeners: function() {
// Add all event listeners having to do with buttons here
}
}
return self;
});
automationPageWrapper.listeners.btnListeners();
});
Why isn't this attaching the event listeners?
Is there a better way to be formatting/calling this?
Is this a professional method for setting up JavaScript code?
I tested the event listeners by taking the functions and posting them into the Chrome console, so I think they work.
The full text, since some people like reading through all of it:
// Global namespace for the Page Functions
window.addEventListener("onload", function() {
var automationPageWrapper = (function() {
var self = {};
// Namespace for event listeners
self.evtListeners = {
// Function to change the color of a selected button
btnColorChange: function(formName) {
var elementsByName = document.getElementsByName(formName);
for (var i = 0; i < elementsByName.length; i++) {
if (elementsByName[i].className == "active") {
elementsByName[i].className = "inactive";
break;
}
}
},
// Add the event listeners
listeners: {
btnListeners: (function () {
document.getElementById('sidebar').addEventListener("click", function(e){
self.evtListeners.btnColorChange('sidebuttons');
e.target.className = "active";
});
})()
}
}
return self;
})();
automationPageWrapper.listeners.btnColorChange();
});
I'm trying to get a textbox to enlarge when focused
The relevant html code is
<input class="tbox" name="q" type="text" />
Since tbox is a catchall for every textbox in the page, I have to work with the name.
I tried this javascript
window.onload = init();
function init()
{
var arr = new Array();
arr = document.getElementsByName("q");
var querybox = arr[0];
querybox.addEventListener('onfocus', wasclicked, false);
querybox.addEventListener('onblur', lostfocus, false);
}
function wasclicked(form)
{
form.q.style['width'] = '500px';
}
function lostfocus(form)
{
form.q.style['width'] = '276px';
}
Debug console tells me I can't use addEventListener on an undefined.
I'm not familiar with javascript, so I tried [0].value as well to no avail.
There are several different issues. First off, you need to use:
window.onload = init; // assign function reference to .onload to call later
instead of:
window.onload = init(); // calls init() immediately and assigns return value to .onload
This is a very common JS mistake. The way you have it, you are calling init() immediately (before the page has loaded) and assigning its return value to window.onload which won't work.
You want to assign a function reference to window.onload. A function reference is the name of the function WITHOUT any parens after it. Adding parens instructs the JS interpreter to execute the function NOW. Assigning just the name puts a pointer to the function into window.onload so it can be called later when the onload event fires.
You also have to fix your event handler callbacks because the form is not what is passed to them. The argument to an event handler is the Event object. The object that caused the event will be in this or event.target:
function wasclicked(e) {
this.style.width = '500px';
}
function lostfocus(e) {
this.style.width = '276px';
}
And, the event names are "blur" and "focus" so you need to change this:
querybox.addEventListener('onfocus', wasclicked, false);
querybox.addEventListener('onblur', lostfocus, flase);
to this:
querybox.addEventListener('focus', wasclicked, false);
querybox.addEventListener('blur', lostfocus, flase);
Combining everything and doing a little simplification, the whole thing should look like this:
window.onload = init;
function init() {
var querybox = document.getElementsByName("q")[0];
querybox.addEventListener('focus', wasclicked, false);
querybox.addEventListener('blur', lostfocus, false);
}
function wasclicked(e) {
this.style.width = '500px';
}
function lostfocus(e) {
this.style.width = '276px';
}
Note that onfocus is the the event handler, but the event itself is focus.
function init()
{
arr = document.getElementsByName("q");
var querybox = arr[0];
querybox.addEventListener('focus', wasclicked, false);
querybox.addEventListener('blur', lostfocus, false);
}
function wasclicked(e)
{
e.target.style.width = '500px';
}
function lostfocus(e)
{
e.target.style.width = '276px';
}
window.onload = init();
As you can see, the event itself contains the elemet so there's no need to add any other variable.
Just know that addEventHandler won't work on all browsers.
Try this:
window.onload = init();
function init()
{
var arr = document.getElementsByName("q");
var querybox = arr[0];
querybox.addEventListener('onfocus', wasclicked, false);
querybox.addEventListener('onblur', lostfocus, flase);
}
function wasclicked(form)
{
form.q.style['width'] = '500px';
}
function lostfocus(form)
{
form.q.style['width'] = '276px';
}
All,
I am really stuck/ confused at this point.
I have an array with 6 items in it. Each item in the array is dynamically filled with elements using jquery '.html' method. However, I cannot seem to be able to attach/ bind an event to this dynamically created variable.
As soon as the browser gets to the problem line (see the area labeled 'PROBLEM AREA'), I get a 'undefined' error, which is really confusing as all the previous code on the very same variable works just fine.
var eCreditSystem = document.getElementById("creditSystem");
var i = 0;
var eCreditT = new Array(6); // 6 members created which will be recycled
function createCreditTransaction () // func called when a transaction occurs, at the mo, attached to onclick()
{
if (i < 6)
{
eCreditT[i] = undefined; // to delete the existing data in the index of array
addElements (i);
} else
if (i > 5 || eCreditT[i] != undefined)
{
...
}
}
function addElements (arrayIndex) // func called from within the 'createCreditTransaction()' func
{
eCreditT[i] = $(document.createElement('div')).addClass("cCreditTransaction").appendTo(eCreditSystem);
$(eCreditT[i]).attr ('id', ('trans' + i));
$(eCreditT[i]).html ('<div class="cCreditContainer"><span class="cCreditsNo">-50</span> <img class="cCurrency" src="" alt="" /></div><span class="cCloseMsg">Click box to close.</span><div class="dots"></div><div class="dots"></div><div class="dots"></div>');
creditTransactionSlideOut (eCreditT[i], 666); // calling slideOut animation
console.log(eCreditT[i]); // this confirms that the variable is not undefined
/* ***** THE PROBLEM AREA ***** */
$(eCreditT[i]).on ('click', function () // if user clicks on the transaction box
{
creditTransactionSlideBackIn (eCreditT[i], 150); // slide back in animation
});
return i++;
}
Try this:
$(eCreditT[i]).bind('click', function() {
creditTransactionSlideBackIn(eCreditT[i], 150);
});
Edit: use ++i instead of i++ like this:
return ++i;
/*
or
i += 1;
return i;
*/
retrurn ++i performs the increment first then return i after the increment.
While return i++ return i then icrement it.
Try to add click event out of addElements() function and try once.
Nonsense create an element using JavaScript and then use jQuery function to transform it into a jQuery object. You can let jQuery create the element directly for you.
eCreditT[i] = $('<div>').addClass("cCreditTransaction").appendTo(eCreditSystem);
Also, since eCretitT[i] is already a jQuery element, no need to call the jQuery function again.
eCreditT[i].on('click', function () {
creditTransactionSlideBackIn(eCreditT[i], 150);
});
If you already tried on, bind, live and click methods, then maybe the called function is your problem. Try to put a console.log() or an alert() inside the function to make sure the click event is actually happening. If it happens then the function creditTransactionSlideBackIn() is your problem.
EDIT
The problem is when the event takes place, i is not the original variable anymore.
function addElements (arrayIndex)
{
eCreditT[i] = $('<div>').addClass("cCreditTransaction").appendTo(eCreditSystem);
eCreditT[i].attr ('id', ('trans' + i));
eCreditT[i].data ('id', i); // Store the id value to a data attribute
Then when you call the function you can refer to the data attribute instead of the i variable:
/* ***** THE PROBLEM AREA ***** */
eCreditT[i].on ('click', function () // if user clicks on the transaction box
{
creditTransactionSlideBackIn ($(this).data('id'), 150); // slide back in animation
});
return i++;
}
try to bind parent div and then use if($e.target).is('some')){}, it will act as .live, like this:
$(eCreditSystem).bind('click', function (e){
if($(e.target).is('.cCreditTransaction')) {
creditTransactionSlideBackIn ($(e.target), 150);
}
});
of course you'll need in a minute larger if for checking if clicked dom el is a child of .cCreditTransaction, like this:
if($(e.target).parents().is('.cCreditTransaction')){}
Try this:
$(eCreditT[i]).live('click', function() {
creditTransactionSlideBackIn(eCreditT[i], 150);
});
I am trying to make a mouse roll-over. i.e when user places the pointer on the image mouse over event is triggered and the next image from the array comes over.But nothing is happening when i am running this script :
window.onload = startRollOver;
var pictures = new Array("1.jpg","2.jpg","3.jpg","4.jpg","5.jpg","6.jpg","7.jpg","8.jpg");
var i = 0;
function startRollOver() {
document.getElementById("picture").src.onmouseover = createRollOver();
}
function createRollOver() {
if(i<=7)
return pictures[i++];
if(i>7) {
i=0;
return pictures[i];
}
}
Where am i going wrong ?
.src.onmouseover does not make much sense. You should assign a function to onmouseover so that the function gets called when the mouse moves over the element:
document.getElementById("picture").onmouseover = function() { // is executed when mouse is over element
this.src = createRollOver(); // each time it is called, change the src
};
Also, you can use a more convenient way of declaring arrays:
["1.jpg", "2.jpg", ...]
You're setting "onmouseover" on the string "src" instead of on the DOM element. You need to set the event on the DOM element.
window.onload=startRollOver;
function startRollOver() {
document.getElementById("picture").onmouseover = function (e) {
e.target.src = createRollOver();
};
}
function createRollOver() {
// ...
}