JavaScript - Class Instance Problem
I have created a class providing various functions called BaseBrowser and the class definition by using prototype.
Specific browser implementations are then acheived by extending BaseBrowser (eg as 'FF' for Firefox) as shown below. The window alert(); function is overridden for alternate message box popup (using layers in the same window). The function 'browser.customAlert()' can be called from either any code or an actual 'alert()' function. However whenever it is called the value of 'someVar' as defaulted back to the new instance value of false despite the instance 'browser' having already set it to true as it were a new instance. Why is this occuring as it should remember its state between function calls ? Code: var browser; function BrowserBase(){ //instance variables this.someVar=false; function customAlert(){ this.someVar=true; // . . . other custom alert code } } function browserLink(){ BrowserBaseFF2p0.prototype=new BrowserBase();//inherit BrowserBaseFF2p0.prototype.constructor=BrowserBase; browser=new BrowserBaseFF2p0(); } function BrowserBaseFF2p0(){ BrowserBase.call(this);//call parent constructor //override generic functions for enhancement if(document.getElementById){ window.alert=function(txt){ browser.customAlert(txt); } } } Similar TutorialsHello, I am new with Javascript and running into this problem that I don't understand. I define a base class that only contains an array "elements", and a derived class that contains nothing more (for simplicity): Code: function baseClass() { this.elements = new Array; } function derivedClass() { } derivedClass.prototype = new baseClass; Then I create two instances of the derived class, and add two elements in each: Code: a = new derivedClass(); a.elements.push("A"); a.elements.push("B"); b = new derivedClass(); b.elements.push("C"); b.elements.push("D"); When I examine the contents of these arrays, I see that both a.elements and b.elements contain {"A","B","C","D"} ! I.e. as if the two arrays are in fact the same array! But these are two separate instances of the class, I expect two separate arrays. Note that if instead I use the base class: Code: a = new baseClass(); a.elements.push("A"); a.elements.push("B"); b = new baseClass(); b.elements.push("C"); b.elements.push("D"); then I get a.elements = {"A","B"} and b.elements = {"C","D"}, as I would expect. Could someone explain to me the problem with using the derived class? Thank you, Stephanos Hi the Is it possible to probe the name of the variable assigned to an object instance in JavaScript? For example: Code: function house(){ } var bobhouse=new house() if (instancename=="bobhouse") //do something In other words, can I do some sort of string comparison on the variable name "bobname", so I know it's actually called "bobname"? I feel I'm asking how to have a variable recognize itself as a variable. Is there a way that I can run a second set of this script on the same page at the same time? If I want a 2nd instance of this script to run on the same page...what values would I need to rename in the 2nd instance? When I try to place this script a second time it only shows the 2nd scripts values or banner ads... I'm trying to make a Banner rotation placement on my sites inner pages (It's a Wordpress powered site) One Set of Banners that ROTATE directly Above Another Set... I like this script since it allows for a Random order on each page load and will ALSO cycle through Each Banner once before repeating the order, That way Each Advertiser will get seen before another is seen a second or third time... I know there are plug-ins for wordpress for advertising, but I have not found any that will rotate out the banners every x niumber of seconds, like this does... Is there a way that I can run a second set of this script on the same page at the same time? <script type="text/javascript"> // Flexible Image Slideshow- By JavaScriptKit.com (http://www.javascriptkit.com) // For this and over 400+ free scripts, visit JavaScript Kit- http://www.javascriptkit.com/ // This notice must stay intact for use var ultimateshow=new Array() //ultimateshow[x]=["path to image", "OPTIONAL link for image", "OPTIONAL link target"] ultimateshow[0]=['http://www.rockinghamcountymerchants.com/CraigTravis/CraigTravis250x250.jpg', 'http://tcraigtravis.com/', '_new'] ultimateshow[1]=['http://www.rceno.com/RCENO/bannerads/elizabethspizza/elizabethspizza250x250.jpg', 'http://www.rceno.com/RCENO/advertisers/elizabethspizza/index.html', '_new'] ultimateshow[2]=['http://www.rceno.com/RCENO/bannerads/gavinsmightychamps/gavin250x250.jpg', 'http://www.gavinsmightychamps.com/index.html', '_new'] ultimateshow[3]=['http://www.rceno.com/RCENO/bannerads/redrivergrill/RedRiver2420-250x250.jpg', 'http://www.rockinghamcountymerchants.com/redrivergrill', '_new'] ultimateshow[4]=['http://www.rceno.com/RCENO/bannerads/qualitycleaners/QC250x250-011510.jpg', 'http://www.rockinghamcountymerchants.com/qualitycleaners', '_new'] //configure the below 3 variables to set the dimension/background color of the slideshow var slidewidth="250px" //set to width of LARGEST image in your slideshow var slideheight="250px" //set to height of LARGEST iamge in your slideshow var slidecycles="continous" //number of cycles before slideshow stops (ie: "2" or "continous") var randomorder="yes" //randomize the order in which images are displayed? "yes" or "no" var preloadimages="yes" //preload images? "yes" or "no" var slidebgcolor='white' //configure the below variable to determine the delay between image rotations (in miliseconds) var slidedelay=9000 ////Do not edit pass this line//////////////// var ie=document.all var dom=document.getElementById var curcycle=0 if (preloadimages=="yes"){ for (i=0;i<ultimateshow.length;i++){ var cacheimage=new Image() cacheimage.src=ultimateshow[i][0] } } var currentslide=0 function randomize(targetarray){ ultimateshowCopy=new Array() var the_one var z=0 while (z<targetarray.length){ the_one=Math.floor(Math.random()*targetarray.length) if (targetarray[the_one]!="_selected!"){ ultimateshowCopy[z]=targetarray[the_one] targetarray[the_one]="_selected!" z++ } } } if (randomorder=="yes") randomize(ultimateshow) else ultimateshowCopy=ultimateshow function rotateimages(){ curcycle=(currentslide==0)? curcycle+1 : curcycle ultcontainer='<center>' if (ultimateshowCopy[currentslide][1]!="") ultcontainer+='<a href="'+ultimateshowCopy[currentslide][1]+'" target="'+ultimateshowCopy[currentslide][2]+'">' ultcontainer+='<img src="'+ultimateshowCopy[currentslide][0]+'" border="0">' if (ultimateshowCopy[currentslide][1]!="") ultcontainer+='</a>' ultcontainer+='</center>' if (ie||dom) crossrotateobj.innerHTML=ultcontainer if (currentslide==ultimateshow.length-1) currentslide=0 else currentslide++ if (curcycle==parseInt(slidecycles) && currentslide==0) return setTimeout("rotateimages()",slidedelay) } if (ie||dom) document.write('<div id="slidedom" style="width:'+slidewidth+';height:'+slideheight+'; background-color:'+slidebgcolor+'"></div>') function start_slider(){ crossrotateobj=dom? document.getElementById("slidedom") : document.all.slidedom rotateimages() } if (ie||dom) window.onload=start_slider </script> In Other words I would have one set of 5 ads rotating and directly below it another set of 5 Ads Hi All, i have thie following code Code: searchValue=document.getElementById('keyword').value;searchValue=searchValue.replace(" ", "_"); and if searchValue = this is my title the above code returns this_is my title instead of this_is_my_title any ideas? EDIT ==== ok solved it this works Code: searchValue=searchValue.replace(/ /gi, "_"); many thanks Luke Hey, I have made/modifying a script that I can create AJAX objects on the fly. It is working fine in Chrome, FF, Opera, Safari but not IE -.- IE = nightmare Code: function ajax_object() { this.receive = function(serverAJAXpage, whileLoading, onDone, dataIntoDivID) { this.xmlHttp = createAjaxObject(); this.serverAJAXpage = serverAJAXpage; this.xmlHttp.open("GET", this.serverAJAXpage, true); this.xmlHttp.send(); this.xmlHttp.onreadystatechange = function() { if (this.readyState == 1) { eval(whileLoading); //document.getElementById(mydiv).innerHTML=this.responseText; } if (this.readyState == 4) { eval(onDone); if (typeof dataIntoDivID != "undefined") { document.getElementById(dataIntoDivID).innerHTML = this.responseText; } } } } } function createAjaxObject() { var xmlHttp=null; try { xmlHttp=new XMLHttpRequest(); } catch (e) { try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } There is the function that handles the object and here is the objects being used: Code: <script> var onlineUsersAJAX = new ajax_object(); onlineUsersAJAX.receive('ajax/onlineUsers.php', '', '', 'onlineUsers'); var recentPostsAJAX = new ajax_object(); recentPostsAJAX.receive('ajax/recentPosts.php', '', '', 'recentThreads'); </script> IE throws the error: 'ajax_object' is undefined Thank you to anyone that can help =) How to I create the following code... Code: #moving { position:absolute; float:right; top:100px; left:50px; } #movingword { position:absolute; float:right; top:0px; left:0px; } ... and this code ... Code: <div id="movingword"> <font color="yellow"><font size="3"><b>This is the place</b></font><br>Welcome!</font> </div> ... programmatically using Javascript? (I will need a X number of "movingwords" and "moving", where X is a number and examples are "movingwords0", "movingwords1", "movingwords2" ... movingwordsX) Here the full code: Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="language" content="english"> <meta http-equiv="Content-Style-Type" content="text/css"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <title></title> <style type="text/css"> body { background-color:#000; } #scenery { position:relative; } #moving { position:absolute; float:right; top:100px; left:50px; } #movingword { position:absolute; float:right; top:0px; left:0px; } </style> <script type="text/javascript"> var t=125; var l=20; $(document).ready(function() { document.getElementById("movingword").style.top = t + "px"; document.getElementById("movingword").style.left = l + "px"; }); </script> </head> <body> <font color=white><h1> Hello World </h1></font> <div id="scenery"> <img src="http://www.deshow.net/d/file/travel/2009-10/new-zealand-scenery-738-20.jpg" alt=""> <div id="moving"> <img src="http://cdn1.iconfinder.com/data/icons/gloss-basic-icons-by-momentum/32/bullet-yellow.png" alt=""> </div> <div id="movingword"> <font color="yellow"><font size="3"><b>This is the place</b></font><br>Welcome!</font> </div> </div> </body> </html> 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 I've written a javascript class that displays a popup, but as soon as the code executes the popup vanishes. I've stepped through the code, line by line and there's nothing that "hides" the popup, the DIV that is created by the class, just reverts back to the default configuration generated by the following function: Code: function generateMarkup() { //build markup var newNode = document.createElement( 'DIV' ); newNode.id = IDs.HelpPopup; newNode.style.visibility = 'hidden'; newNode.innerHTML = [ '<div id="popup">', '<div id="inside">', '</div>', '</div>' ].join( '' ); return newNode; } All the changes made to the DIVs via document.getElementById code is completely wiped out. For example: Code: document.getElementById("inside").innerHTML = sText; If I stop processing just before the Class returns to the form, the generated code is exactly as I expect it to be with all the dynamic modifications. The class is triggered by an onClick event on a BUTTON. I've tried to put a "sleep" function in after executing the function that modifies the DIVs, but that seems to execute before the function, not after, so the popup just flickers into existence and then vanishes. Can anyone give me any hint(s) as to how to stop this happening. If the value is negative it should be in red, otherwise it should be in green. It looks like JavaScript completely ignores the css class. Help please. Code: <html> <head> <title>Prva</title> <style type="text/css"> span.Pozitivno { color:green; font-weight:bold; } span.Negativno { color:red; font-weight:bold; } </style> <script type="text/javascript"> function vpisi_stevila() { var a; var b; //Vnos spremenljivk a=prompt("Vnesi stevilo a:") b=prompt("Vnesi stevilo b:") a=a*1 //S tem spremenimo string v int b=b*1 //Izpis stevil if(a<0) { document.write("A:<span class='Negativno'> " + a + " </span> <br />"); } else { document.write("A:<span class='Pozitivno'> " + a + " </span> <br />"); } if(b<0) { document.write("A:<span class='Negativno'> " + a + " </span> <br />"); } else { document.write("A:<span class='Pozitivno'> " + a + " </span> <br />"); } document.write("Vsota:", a+b, "<br />"); document.write("Razlika:", a-b, "<br />"); document.write("Mnozenje:", a*b, "<br />"); document.write("Deljenje:", a/b, "<br />"); document.write("Ostanek:", a%b, "<br />"); if(a>b) //Ce je A vecje od B { document.writeln("A je <b>večje </b> od b") } if(a<b) //Ce je B vecje od A { document.writeln("A je <b>manjse </b> od b") } if(a==b) //Ce sta enaka { document.writeln("A je <b>enako </b> b") } } </script> </head> <body onload="vpisi_stevila()"> </body> </html> Why is the callwhy is the slice method only a method of an Array instance? The reason why I ask is because if you want to use it for the arguments property of function object, or a string, or an object, or a number instance, you are forced to use Array.prototype.slice.call(). And by doing that, you can pass in any type of object instance (Array, Number, String, Object) into it. So why not just default it as a method of all object instances built into the language? In other words, instead of doing this: Code: function Core(){ var obj = {a : 'a', b : 'b'}; var num = 1; var string = 'aff'; console.log(typeof arguments);//Object console.log(arguments instanceof Array);//false var args1 = Array.prototype.slice.call(arguments); console.log(args1); var args2 = Array.prototype.slice.call(obj); console.log(args2); var args3 = Array.prototype.slice.call(num); console.log(args3); var args4 = Array.prototype.slice.call(string); console.log(args4); Core('dom','event','ajax'); Why not just be able to do this: Code: function Core(){ var obj = {a : 'a', b : 'b'}; var num = 1; var string = 'aff'; var args = arguments.slice(0); var args2 = obj.slice(0); var args3 = num.slice(0); var args4 = string.slice(0); //right now none of the above would work but it's more convenient than using the call alternative. } Core('dom','event','ajax'); Why did the designers of the javascript scripting language make this decision? Thanks for response. Hi all, On my site each page is composed by header, contents and bottom. Each part, located respectively at header.php, content1.php, content2.php, ... and bottom.php, is included in page.php. I have a menu, that is the same for all pages, on header.php: Code: <ul class="site-nav"> <li><a href="home.php" class="" name="Home"></a></li> <li><a href="page2.php" class="" name="OK"></a></li> </ul> I'd like to set a class in order to have its corresponding menu with this class="act" for each content.php. I tried this but it doens't work: I add this in content1.php Code: <!-- act for site-nav --> <script language="javascript" type="text/javascript">function changeClass() { document.getElementByName("Home").setAttribute("class", act); } </script> and this in top.php Code: <ul class="site-nav"> <li><a href="home.php" class="changeClass()" name="Home"></a></li> <li><a href="page2.php" class="changeClass()" name="OK"></a></li> </ul> Please help me, I don't understand anything of javascript . Hi, I need to change my class, but this isn't doing it for me and I don't see why. No error messages, but nothing happens. Code: .myClass { background-color: yellow; } document.getElementById("myId").setAttribute("class","myClass"); Thank You in Advance for Your Help, Lou Alright I have never really created a class before and I have to for a project. This is what I have so far and I will try to explain the requirements I am looking for thoroughly and what problems I am having. Code: <!doctype html public "-//w3c//dtd html 4.0 transitional//en"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <script language="javascript" type="text/javascript"> function clock () { //Object Constructor this.setT = function() { //Method Set Time //Properties this.currentTime = new Date ( ); this.currentHours = this.currentTime.getHours ( ); this.currentMinutes = this.currentTime.getMinutes ( ); this.currentSeconds = this.currentTime.getSeconds ( ); } clock.prototype.displayTime = function () { clock.setT } } </script> <body> <form name="form1"> <p> <input type="text" rows=7 cols=60 name="currentTime"> <br> <input type="button" value="Set Time" onClick="clock.displayTime();"> <br> <input type="button" value="Display Time" onClick="currentTime.value= completeTime;"> <br> <input type="reset" value="Reset"> </p> </form> </body> </html> The clock class contains: Three Properties: Hours Minutes, Seconds Two Methods setTime (which uses date class to get current time) Must be defined in the constructor displayTime (returns a string displaying current time) Must be defined as a prototype property of constructor The below is a very rough outline, and probably not correct. I've been reading up on objects for the last few hours and can't be very sure of anything yet. Code: function clock() { this.currentTime = new Date ( ); var currentHours = currentTime.getHours ( ); var currentMinutes = currentTime.getMinutes ( ); var currentSeconds = currentTime.getSeconds ( ); this.setTime = function() { } } clock.prototype.displayTime = function ( ) { } I guess my biggest problem now is the outline. Any help would be great hopefully once i get what goes where i can actually start writing the code. I already have the full code to write a basic clock just like this but it doesn't use classes or any of this. I'm a amateur and I've just coded this little script. What it does is quite simple, once you click on the 'theBox' div, it switches from one class to another. I can't help having the feeling that this could have been coded in a lot more simple way than the way I've coded. So I thought that maybe you guys could help me out. (Oh, and by the way, the script works fine in FireFox and IE). Code: <script> function setDivClassName(string){ document.getElementById("divClassName").innerHTML = string; } function theBoxOnClick(){ var classes = new Array(); classes[0] = 'zero'; classes[1] = 'one'; classes[2] = 'two'; var currentClassName = document.getElementById('theBox').className; var currentClassIndex; var nowGoTo; for(var i = 0;i <= classes.length-1;i++){ //alert(classes[i]); if(classes[i] == currentClassName){ currentClassIndex = i; nowGoTo = currentClassIndex + 1; } } if(classes[nowGoTo] == undefined){ nowGoTo = 0; } document.getElementById('theBox').className = classes[nowGoTo]; setDivClassName(classes[nowGoTo]); } </script> <style> .zero{width:100;height:100;background-color:black;color:white;padding:10;border-style:solid;border-color:red;border-width:2} .one{width:100;height:100;background-color:yellow;color:red;padding:10;border-style:solid;border-color:red;border-width:2} .two{width:100;height:100;background-color:red;color:yellow;padding:10;border-style:solid;border-color:red;border-width:2} </style> <body onLoad="setDivClassName('zero')"> <div id="theBox" class="zero" onClick="theBoxOnClick()"> This DIV's Class is <div id="divClassName"></div> </div> Hello everybody. For the moment im locking for a JavaScript-document. That will be working like this... When we are push on a link, for example to username. So will it coming up a box "<div class="profile_class"></div> From to beeing visibility: hidden; display: none; To be visibility: visibile; display: block; .profile_class { float: left; width: 300px; height: 250px; margin-top: 2px; margin-left: 2px; position: absolute; visibility: hidden; display: block; background-color: #151515; } .profile_class_inactive { visibility: visible; display: none; } When we are push on the mouse outsite the "profile_class" will it beeing closing/invisbile. But when we have it active something like "profile_class" so will it show uz... <ul> <li>Send a message</li> <li>Add contact</li> <li>Block the contact</li> </ul> And on the right site, will it beeing showing uz a little avatar. Can you please help me with this one? hey I want to get the href via attributes of this a tag & then this href to be set to a variable So, I have this javascript that works just fine... But... PHP Code: <script language="javascript"> function addBtn() { element = document.createElement("input"); element.setAttribute("type", 'button'); element.setAttribute("value", 'Track'); element.setAttribute("name", 'element'); element.onclick = function() { alert("Tracking"); }; var btn = document.getElementById("gs-track-btn"); btn.appendChild(element); } </script> <div id="gs-track-btn"></div> How would I target that div if the " gs-track-btn " id was a class? I have a list like this:
Code: <tr> <td>Some Text One</td> </tr> <tr> <td>Some Text One</td> </tr> <tr> <td>Some Text One</td> </tr> When I click a radio button, I want the text to "dim", that is, change color. So I have two CSS classes, on and off. Here's the JS PHP Code: function enableCFFID() { document.cartform.cffid.disabled=false; document.getElementsName('cffidtext').class="cffidon"; } function disableCFFID() { document.cartform.cffid.disabled=true; document.getElementsByName('cffidtext').class="cffidoff"; } But, this does not work. What am I doing wrong??? I wanted to design and implement a program that accepts from the user the numerator and denominator of a fraction and prints the simplified form of the fraction. So basically have TWO objects of the Fraction Class. The output line should look something like this: The fraction 3615/7230 simplifies to 1/2. but then I was wondering if it was possible to place it in a box-like look. So something like this... Sample output: *--------------------------------------* *The fraction 3615/7230 simplifies to 1/2.* *--------------------------------------* *---------------------------------* *The fraction 5/10 simplifies to 1/2.* *---------------------------------* so the box should fit with words. I currently have a navigation bar with CSS. It sits by itself in a frame so it doesn't change with the other page turns. So I'm trying to figure out how to set each link class="active" since it always stays on the same page. I'm thinking javascript will be my friend. Is there an onclick function that can be defined? I'm not new to webpages but new to learning javascript, instead of borrow someone's code. I didn't know how to approach this code because I think I need it to say: If Onclick, then set to class="active", otherwise (then), set class="nothing" or anything to this regard. I was not sure how I could approach that code and how to fit into the UL/LI html code I currently have setup as well as the head code. Example code: (I have 3 frames called head, form, and body. Head is the nav bar where this code sits.) Code: <ul class="menu"> <li><a href="choose.htm" class="active"><span>Home</span></a></li> <li><a href="search.htm" target="form" onClick="top.body.location='http://www.google.com';"><Span> Google</span></a></li></ul> With my CSS code, the "menu" defines some colors/setup, as so does Span and class="active". As a bonus, if you could teach me instead of just help me, it would help me help others. |