JavaScript - Addeventlistener In Custom Object
I'm trying to understand how a custom object can call a function within itself. Say I have something like this:
Code: function functiontest() { this.prop1 = '', this.prop2 = '', this.options = {initiallevels:0}, this.prop3 = '/blah', this.prop4 = true, this.function4 = function(x) { console.log(x) }, this.init = function(options) { this.uid=options.uid this.t=options.target document.getElementById(this.t).addEventListener('click',function(){this.uid.function4(this.t)},false) } } myfun1=new functiontest myfun1.init({uid:'myfun1',target:'target1'}) myfun2=new functiontest myfun2.init({uid:'myfun2',target:'target2'}) And the html: Code: <html> <head></head> <body> <div id="target1">T1</div> <br> <div id="target2">T2</div> </body> </html> I don't know what to put in the part in bold to set the click event listener and have it call function4 within the functiontest object. I've tried a bunch of different things and nothing worked. Please help, thanks! Similar TutorialsHi all. I'm developing After Effects scripts using their Extendscript language - essentially just Javascript with various extensions. I've defined a class, called ScriptSetting, which handles reading and writing of user settings to a prefs file. For example I create a ScriptSetting variable as follows: Code: var mySetting = new ScriptSetting("myScript", "thisSettingKey", 200); This calls the ScriptSetting constructor function: Code: function ScriptSetting(sectionName, keyName, defaultValue) { this.sectionName = sectionName; // Store the type of this setting for conversion later this.defaultType = defaultValue.constructor; // Convert any type to a string value for storing defaultValue = defaultValue.toString(); this.keyName = keyName; if(!app.settings.haveSetting(this.sectionName, this.keyName)) { this.value = defaultValue; this.saveSetting(); } else this.value = this.getSetting(); } This calls some of Extendscript's built-in functions, like app.settings.haveSetting() This all works fine - I can then later access mySetting's value with, for example alert(mySetting.value) since I've defined value as part of the class constructor function. However what I'd ideally like to do, if at all possible is to lose the .value part and just be able to access the setting value directly from the setting variable, so in this case alert(mySetting). At the moment, this will just return object Object. Naturally this is because mySetting is an instance of the ScriptSetting object. But I wondered if you can spoof this with a different type (i.e. Array or Number) when accessing it as part of a statement e.g. if(mySetting == 200) { // do something } but still retain all its prototyped methods, e.g. Code: mySetting = 300; mySetting.saveSetting(); Is this possible in Javascript? It's not a deal-breaker - I just want to make my code a bit more readable. Many thanks in advance, Christian I'm trying to add an event handler for to my body, and for some reason which I can't figure out, it only works on Google Chrome. I wouldn't expect it to work in IE, but am wondering why it's not working in Firefox. Here's the relevant parts of the code: Javascript (in an external file) Code: var body = document.body; body.addEventListener("load", Foo(), false); function Foo(){ addEventListener(document.getElementsByName("start"),"click", alert("hello"), false); } HTML Code: <html> <head> <title>BREAKOUT!</title> <script src="breakout.js" type="text/Javascript" > </script> <LINK REL="stylesheet" HREF="breakout.css" TYPE="text/css"> </head> <body id="body"> <!-- etc.... --> Okay, I'm really am not getting this. So I came here hopefully for some help. I'm just trying to register a simple click event onto a input element with addEventListener and attachEvent... My code: Code: function addEvent(type, func, elem) { var netscape = document.getElementById && !document.all; var ie = document.all; if(netscape) { elem.addEventListener(type, func, true); } else if(ie) { elem.attachEvent('on'+type, func); } } //Which is then call by addEvent('click', someFunction, theElementObject); So say I had the following code like so: Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <title>Example</title> <link rel="stylesheet" type="text/css" href="./css/global.css" /> <script type="text/javascript"> function addEvent(type, func, elem) { var netscape = document.getElementById && !document.all; var ie = document.all; if(netscape) { elem.addEventListener(type, func, true); } else if(ie) { elem.attachEvent('on'+type, func); } } function clearTxt() { var username = document.getElementById('username'); if(username.value == 'Screen Name') { username.value = ''; } } addEvent('click', clearTxt, document.getElementById('username')); </script> </head> <body> <label for="username">Username:</label> <input name="username" type="text" value="Screen Name" id="username" maxlength="20" /> </body> </html> From what I can see and what I understand it should just on event of a click on the username input it should clear the username field. But instead I get a error message from IE saying, "null is null or not a object"???? Like that was any help. So could someone please help me figure out my misunderstanding of this method? Thanks, Jon W I have created this statement and it does its job but not very efficient. How can I put this in a loop and populate the information that I want anonymously? I do not want to copy and paste this for every (id) there is on this page. Locate id get value and use same value to change the bgColor of the page Code: <input id="red" value="red">red <input id="green" value="green">green <script> document.getElementById('red').addEventListener('click', function (e) { inputColor = e.target.getAttribute('value'); document.bgColor = inputColor; }, true); <script> Your help will be much appreciated! Thanks! Is it possible to add events using addEventListener to multiple radio buttons with same id ? <input id="radId" type="radio" value="0" name="radioname">No <input id="radId" type="radio" value="1" name="radioname">Yes I tried to attach event using document.getelementByID BUT it always picks the first radio button. Is there a way around this, any help would be highly appreciated. Thanks Hi folks, I'm having problem setting up event handling using member functions. Consider the following code snippet: Code: function Widget() { ... this.register = function() { ... document.getElementById(this.id).addEventListener('click', this.default_click_handler, false); } this.default_click_handler = function(event) { this.do_something_useful(); //<--??? } this.do_something_useful = function() {...} } However I don't manage to call do_something_useful(), I get a this.do_something_useful() is not a function error. What am I doing wrong? Any help is appreciated, Thanks, A. Code: function offPar(){ alert(this.offsetParent.id); } function init(){ var mine = document.getElementById("mid"); var other = document.getElementById("inner"); mine.addEventListener("click", offPar, false); other.addEventlistener("click", offPar, false); } window.addEventListener('load', init, false); HTML : <div id = "content"> <div id = "mid"> <div id = "inner"> <p class = "par"> </p> </div> </div> </div> I can add an event listener to the #mid div but I can't to the #inner div. Anyone now why this is? Sorry I can't provide more info. That's all I Know! TTFN John Hi, I have the following code: Code: function addHandlers() { var elementList = new Array(); elementList.push(new Element("newhomesdiv", "images/newhomes.png", "images/newhomes-over.png")); elementList.push(new Element("additionsdiv", "images/additions.png", "images/additions-over.png")); elementList.push(new Element("homeimprovdiv", "images/homeimprove.png", "images/homeimprove-over.png")); elementList.push(new Element("aboutusdiv", "images/aboutus1.png", "images/aboutus-over1.png")); for(var i = 0; i < elementList.length; i++) { var curNode = document.getElementById(elementList[i].parentId).firstChild; var item = elementList[i]; if(curNode) { /*if(curNode.addEventListener) { curNode.addEventListener("mouseover", function(){makeCallback(item.parentId, item.hoverImage)}, false); curNode.addEventListener("mouseout", function(){makeCallback(item.parentId, item.regImage)}, false); } else if(curNode.attchEvent) { curNode.attachEvent("onmouseover", function(){makeCallback(item.parentId, item.hoverImage)}); curNode.attachEvent("onmouseout", function(){makeCallback(item.parentId, item.regImage)}); } else { curNode["onmouseover"] = makeCallback(item.parentId, item.hoverImage); curNode["onmouseout"] = makeCallback(item.parentId, item.regImage); }*/ curNode.onmouseover = makeCallback(item.parentId, item.hoverImage); curNode.onmouseout = makeCallback(item.parentId, item.regImage); } } } function makeCallback(parId, image) { return function() { changeImage(parId, image); }; } function changeImage(parId, image) { document.getElementById(parId).firstChild.src = image; } The curNode.onmouseover = makeCallback(item.parentId, item.hoverImage); works, but I want to use addEventListener and fallback to the other methods. I don't understand why the addEventListener and attachEvent parts doesn't work. Any ideas? Every time i click on one of the said elements, it puts "undefined" into the textbox each time i click on an element. it seems to me that the Key_Table[x] is not getting passed correctly. How do i make sure that this is getting passed correctly? Here's my Code: Code: <script type='text/javascript'> // Startup Script if (document.addEventListener) { document.addEventListener("DOMContentLoaded", LoadEventListeners, false); } function LoadEventListeners() { var Key_Table = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"]; // Create event Listeners for the alphabetic keys for(var x = 0; x < Key_Table.length; x++) { Key_Table[x] = document.getElementById(Key_Table[x]); Key_Table[x].addEventListener("click", function(){ InsertChar(Key_Table[x]); }, false); } } function InsertChar(Char) { alert("Char is:" + Char); // Textbox data document.getElementById('TextData').value = document.getElementById('TextData').value + Char; } </script> On my site we have image galleries that pop up over top of the page in a higher z-index and position:fixed, and another div between the gallery and background with opacity set to about 85%. The image gallery div has a close button, and I was asked to make the gallery also close by pressing ESC, so I added this: igevt=function(evt){checkclosegal(evt)} window.addEventListener('keypress',igevt, false) and checkclosegal: function checkclosegal(evt) { if(evt.keyCode==27) { closebgeagal() window.removeEventListener('keypress',igevt, false) } } This works perfectly in Firefox and Opera, but Chrome and Safari don't fire the event (not worried about ie right now - I know it uses attachEvent). Could it have something to do with the gallery being in a higher z-index? Please help, thanks! Hi there Im trying to create a function where i pass two element id's and my script populates it with events and anything else it may need to run but what i am finding is that i cant use this so that the instance of the object is kept what ends up happening is nothing at all what i would like to have happen is the code to work somthing like this... Code: <div id="iAmTheTargetId"> </div> <div id="iWillHoverOverYouId"> </div> <script type="text/javascript"> var element = new hoverBox('iAmTheTargetId','iWillHoverOverYouId'); </script> and simply running that would then create the equivalent of doing Code: <div id="iAmTheTargetId" onmouseover="element.activate()" onmouseout="element.deactivate()" onmousemove="element.update(event)> </div> <div id="iWillHoverOverYouId"> </div> <script type="text/javascript"> var element = new hoverBox('iAmTheTargetId','iWillHoverOverYouId'); </script> But of course the code above won't actual add onmouseover and etc it just so you can see what i'm trying to achieve Code: /* * triggerId * the element in which the attributes will be applied to * * hoverBoxid * the element in which will hover around the triggerId */ function hoverBox(triggerId,hoverBoxid){ this.triggerElement = document.getElementById(triggerId); this.hoverBoxElement = document.getElementById(hoverBoxid); if(this.triggerElement == null || this.hoverBoxElement){ return null; } self = this; alert(this.triggerElement); this.triggerElement.addEventListener('mouseover',function(){self.activate();},false); this.triggerElement.addEventListener('mouseout',function(){self.deactivate();},false); this.triggerElement.addEventListener('mousemove',function(){self.update(event);},false); } hoverBox.prototype = { triggerElement : null, hoverBoxElement : null, state : false }; hoverBox.prototype.activate = function(){ this.state = true; }; hoverBox.prototype.deactivate = function(){ if(this.state != false){ this.hoverBoxElement.style.display = "none"; this.state = false; } }; hoverBox.prototype.update = function(evt){ if(this.state != false){ this.hoverBoxElement.style.display = "block"; this.hoverBoxElement.style.position = "absolute"; this.hoverBoxElement.style.top = (evt.clientY + 5)+ "px"; this.hoverBoxElement.style.left = (evt.clientX + 10)+ "px"; } }; A quick note theses function will work by them selfs if you just do Code: <div id="target" onmouseover="aHoverBox.activate()" onmouseout="aHoverBox.deactivate()" onmousemove="aHoverBox.update(event)"> </div> <div id="hover"> </div> <script type="text/javascript"> var aHoverBox = new hoverBox('iAmTheTargetId','iWillHoverOverYouId'); </script> But not quite what I'm after i would like not to have to enter in Code: onmouseover="aHoverBox.activate()" onmouseout="aHoverBox.deactivate()" onmousemove="aHoverBox.update(event)" and have that done by the JavaScript Well i hope every thing makes scene sorry if i repeated my self just making sure you understand me Good day! Here is the problem, setting the slider to the site, here's an example: http://wowslider.com/best-jquery-sli...near-demo.html and do not connect different effects on this slider, such as buttons on the sides and smooth shifting slides. When you see the code generates this error: Uncaught TypeError: Cannot read property addEventListener' of undefined I do not know what this error, help, error on this site: http://uh219381.ukrdomen.com/ Or here's the code: http://uh219381.ukrdomen.com/themes/...1/wowslider.js sorry for my English Hi, every time I try and alert: [ { number:0, secondnumber:0 }, { number:2, secondnumber:1 }, { number:1, secondnumber:2 } ] it just shows [object object], [object object], [object object]. Why is this and what can I do to make the record be shown as it is above in an alert? Thanks. I created a method for displaying an object's properties: Code: renderfunction = false; function showProperty (object, property) { document.write ('<td class="type">' + (typeof object[property]) + '</td>' + '<td class="name">' + property + '</td>'); document.writeln('<td class="value">' + ( (typeof object[property] != 'function') ? object[property] :( (property != 'showProperties') ? ( renderfunction ? object[property]() : ('<span class="self">NOT RENDERED</span>') ) : ('<span class="self">THIS</span>') ) ) + '</td>'); document.writeln('<td class="hasOwnProperty" >' + ( object.hasOwnProperty(property) ? "Local" : "Inherited" ) + '</td>'); if (typeof object[property] == 'function') { document.writeln ('<td class="function">' + object[property] + '</td>'); } else { document.writeln ('<td class="function"> </td>'); } } As long as renderfunction = false, the object is fine coming out of this function. However, if I change renderfunction to true, all my properties become undefined. Why isn't this working as I expect it to? How should I fix it? Thanks in advance, -Brian. I can't get any info from Firebug except that one line, uncaught exception [object Object]. The code fully worked, then I needed to make it dynamically create Sortables from the scriptaculous library based on how many X were in a table in my database, which I've done, and I'm thinking it may be a simple slight parse error of some type, I'm not too good with Javascript, because now my script barely works. I've double checked the script's source code, the PHP variables are exactly what they should be. Code: print<<<HERE Sortable.create('sortlist$box', { tag: 'img', overlap:'horizontal',constraint:false, containment: $list, dropOnEmpty: true, onChange: function(item) { var list = Sortable.options(item).element; if(changeEffect) changeEffect.cancel(); changeEffect = new Effect.Highlight('changeNotification', {restoreColor:"transparent" }); }, onDrop: function(item) { var thing=Sortable.options(item).element.identify(); var anchors = document.getElementById(thing).childNodes.length-2; if(anchors > 20){ alert('This box had 20 creatures in it already, your last action has not been saved.'); window.location.reload(); } else{ new Ajax.Request("saveImageOrder.php", { method: "post", parameters: { data: Sortable.serialize("sortlist$box") } }); } } }); HERE; $box++; } ?> }); </script> if you solve this I'll send ya $10 via paypal Ignore post (if mod, please delete)
Hi all, I'm stumped on finding a way in javascript to create an object factory whose instances are also object factories. In short I want something like that below, but no joy ... any clues? Code: function createClass () { return new createClass() function createClass() { return new createInstance () function createInstance () { //Default properties, values and methods which might later be extended } } } var createDoor = createClass(); var door1 = createDoor(); var door2 = createDoor(); var createChair = createClass(); var chair1 = createChair (); var chair2 = createChair (); Hello together! I generate html code with jsp. In that jsp there a several framesets and frames. And yes i know, frames are not really up to date but it's an old program and i have to deal with it now. Anyway, in the top frameset i have an onload attribute like onload="load()". In the function load i want to access the Element.prototype object. But unfortunately typeof Element gives me "undefined". So i looked a little deeper and found that window.toString() gives me "[object]" and not as expected "[object window]" so somehow my window doesn't know that its construcor is Window. window.construcor is "undefined" as well. And i don't have access to the Element object. I really don't know where the error could be. When the page is loaded and i access the same window over the console, then everything is right. But in my function a can't get access to the objects i need. I also don't know what part of the code could be useful to post here, but maybe someone had a similar problem before? i should say that this problem only occurs in IE8. In IE9 it works perfectly. Has anyone any idea?? I'm writing a program that involves a network of interconnected nodes (or simply objects in my example below). It depends on being able to access properties of an object's linked objects (a bit oddly worded, sorry)... Problem is I'm not sure how to properly access those properties... see below please. <script> //This is an example of a problem im having in my own code... //I want to access the name of the object within the links array wintin the object... var objA = {name: "Object A", links: [objB, objC]}; var objB = {name: "Object B", links: [objC, objD, objE]}; var objC = {name: "Object C", links: [objB]}; var objD = {name: "Object D", links: [objE]}; var objE = {name: "Object E", links: [objD]}; //ex: I want to access the name of Object A's first link... console.log(objA.links[0].name); </script> I'm hoping to get "Object B"... But instead I get: TypeError: Result of expression 'objA.links[0]' [undefined] is not an object. Is there another way around this? Any thoughts are appreciated. Quote: menu: function( a, b ) { $( b ).observe( 'click', function( event ) { event.stop(); if( $( a ).visible() ) { $( a ).hide(); $( b ).removeClassName( 'selected' ); document.stopObserving( 'click' ); } else { $( a ).show(); $( b ).addClassName( 'selected' ); document.observe( 'click', function( e ) { if( e.target.id != a && e.target.id != b && !Element.descendantOf( e.target, $( a ) ) ) { $( a ).hide(); $( b ).removeClassName( 'selected' ); document.stopObserving( 'click' ); } }); } }); $$( '#' + b + ' > a' ).each( function( element ) { element.observe( 'click', function( event ) { $( a ).hide(); $( b ).removeClassName( 'selected' ); document.stopObserving( 'click' ); }); }); } This work's perfrect accept when i use it with others on the menu it leaves the other ones open, how do i get it to close the open one when i open a new menu.. Thanks. |