JavaScript - Simulating Classes In Javascript
Hey all,
I am reading a book called JavaScript patterns. In it, this method is created: Code: var klass = function(Parent,template){ var Child, F, i; Child = function () { if (Child.uber && Child.uber.hasOwnProperty("__construct")) { Child.uber.__construct.apply(this, arguments); } if (Child.prototype.hasOwnProperty("__construct")) { Child.prototype.__construct.apply(this, arguments); } } Parent = Parent || Object; F = function () {}; F.prototype = Parent.prototype; Child.prototype = new F(); Child.uber = Parent.prototype; Child.prototype.constructor = Child; for (i in template) { if (template.hasOwnProperty(i)) { Child.prototype[i] = template[i]; } } return Child; } Does anyone have an understanding of why we instantiate a new F() to the Child prototype rather than instantiate the Parent prototype? As you can see above, we assign Parent prototype to F prototype and then instantiate F() object to Child prototype. I'm not sure why it's being done this way. Code: F.prototype = Parent.prototype; Child.prototype = new F(); Thanks for response. Similar TutorialsHi Guys, What is the best way to create a javascript class that has all its methods and properties private unless I want them to be public? Many thanks for any help, S Hey all, my first post here. I'm primarily a designer but need to get more into the code aspect of things (and will be getting jQuery asap), but at the moment i'm very behind on time on a project and could use some quick help. Basically, I'm making a dynamically loading text box input area for RMA returns for our products. But thats kind of irrelevant, here's my question: I have an external style sheet with only this in it (more will be added later for future sections, thats why im making it it's own "css-forms.css" file: Code: .formpad { padding:3px 3px 3px 3px; } In my main .html, some of my javascript for my dynamic table contains lines like these: Code: var esnImeiInput = "<INPUT type=\"text\" name=\"esn_imei[]\" size=\"20\">"; var invoiceInput = "<INPUT type=\"text\" name=\"invoice[]\" size=\"8\">"; var datePurchaseInput = "<INPUT type=\"text\" name=\"date_purchase[]\" size=\"8\">"; var noteInput = "<INPUT type=\"text\" name=\"notes[]\" size=\"18\">"; var trOpenTag = "<tr>"; var trCloseTag = "</tr>"; var tbOpenTag = "<table>"; var formRows = modelInput + reasonInput + esnImeiInput + invoiceInput + datePurchaseInput + noteInput + "<br />"; for(x=0;x<10;x++) { formRows += modelInput + reasonInput + esnImeiInput + invoiceInput + datePurchaseInput + noteInput + "<br />"; } Where inside those vars (INPUT's) would i REFER to the 'class' of .formpad? Basically I just want to add cellpadding to the table that is being dynamically loaded. If anyone has time to help via IM that'd be cool too, this is pretty easy stuff for true coders. (the test page for all of this is currently at: http://planetcellinc.com/rma-rev726.html Any help appreciated, thanks! -Hrl2k I am trying to work out how to use Google Chrome DevTools to simulate a timeout on a JavaScript file on my site. I can use the 'Toggle Device Mode' to introduce throttling but that doesn't target a specific script. Is there a way to do this with DevTools? I am using Chrome 38. Could someone please explain the difference in these two methods of creating objects: //anonymous self invoking function providing private methods var a_module = (function() { var private_variable = "some value"; function private_function() { //some code } return { public_property: "something" //etc } }() ); //Can use a_module.public_property with this Is there any difference between the above and this: var A_module - new Object(); A_module(property1, property2) = { this.property1 = property1; this.property2 = property2; this.methodName = function(){//code} } A_module.prototype.property = "//property" A_module.newMethod = function() {//code} Are they both just different ways of creating objects with methods and properties? I'm quite new to javascript and don't often understand what I'm reading, so the search results I found didn't seem to help me much. Being such, if this question has been addressed elsewhere, my apologies. On my site, I have a navigation pane with 4 links. Two of these links show collapsable submenus. When one clicks a link, I want the CSS class of that link to change. For the two "real" links, I've just changed the class on the page itself. For the two collapsible menus, I'm trying to employ javascript. Ultimately for these two links, I want the class to change when clicked, and change back when clicked again. Here's the code for the page: Code: <div id="navigation"> <ul> <li><h3><a href="javascript:;" onclick="changeclass(this);" onmousedown="toggleSlide('slidemenu');" class="colmain">COLLAPSIBLE MENU 1</a></h3></li> <div id="slidemenu" style="display:none; overflow:hidden; height:100px;"> <li><h4><a href="#" class="sub">SUBMENU LINK 1</a></h4></li> <li><h4><a href="#" class="sub">SUBMENU LNK 2</a></h4></li> </div> <li><h3><a href="#" class="main">LINK 1</a></h3></li> <li><h3><a href="javascript:;" onclick="changeclass(this);" onmousedown="toggleSlide('slidemenu2');" class ="colmain">COLLAPSIBLE MENU 2</a></h3></li> <div id="slidemenu2" style ="display:none; overflow:hidden; height:100px;"> <li><h4><a href="#" class="sub">SUBMENU LINK 1</a></h4></li> <li><h4><a href="#" class="sub">SUBMENU LINK 2</a></h4></li> </div> <li><h3><a href="#" class="main" >LINK 2</a></h3></li> </ul> </div> Here's the javascript I'm working with, which I adopted from http://www.webdeveloper.com/forum/sh...d.php?t=167660 : Code: /*<![CDATA[*/ var colstatus; function changeclass(obj) { if (colstatus) colstatus.className='colmain'; { obj.className='colmainshow'; colstatus=obj; } else { obj.className='colmain'; colstatus=obj; } } /*]]>*/ I have three questions about this. 1. Seeing as I've been working with javascript for a grand total of six days so far, could you explain the best way to make my code work? What's the significance of colstatus=obj? 2. The javascript works if I leave out the else statement. It will change the class after being clicked, but, of course, doesn't change it back. However, if I click the other collapsible menu, it will change as expected, but the first will revert back to the original class. Why is this happening? 3. Seeing as the code is adopted, I have no idea what /*<![CDATA[*/ and /*]]>*/ mean. Would you explain? Thanks in advance for your patience and answers! Hi, could someone please help. I have this code, and it currently outputs:"name-category" but I need it to output "category-name". Sorry if this is easy, I just keep getting errors! Code: highlightWork : function(workType) { // remove all active classes $(".work").removeClass("active"); for (var x=0;x<workTypes.length;x++) { if (workType.toLowerCase()==workTypes[x][0].toLowerCase()) { $("."+workTypes[x][0]+"-category").addClass("active"); // set current highlight $("."+workTypes[x][0]).addClass("highlight"); } else { // remove current highlights $("."+workTypes[x]).removeClass("highlight"); if (workType.length!=0) { $("."+workTypes[x][0].split(" ")[0]+"-category").addClass("inactive"); } } } }, Hi, I have a question about an oop/class style form of javascript programming. I have stripped the code down to the basic minimum. The problem is I have created two instances of the same class and have entered data into those classes. But as you will see the two separate instances of the class appear to share the same data. How do I get my class structure working so separate instances will retain their separate data? Here is the code: Index.html Code: <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <script type="text/javascript" src="test.js"></script> <script type="text/javascript"> debugger; // Do this because a page resart seems to keep old data function SetGlobals() { var ui; var el; // Arr00 ui = document.getElementById("Arr00"); el = arr0.arrayGet(0); ui.innerHTML = el.m_String; // Arr01 ui = document.getElementById("Arr01"); el = arr0.arrayGet(1); ui.innerHTML = el.m_String; // Arr10 ui = document.getElementById("Arr10"); el = arr1.arrayGet(0); ui.innerHTML = el.m_String; // Arr11 ui = document.getElementById("Arr11"); el = arr1.arrayGet(1); ui.innerHTML = el.m_String; } function MyOnLoad() { SetGlobals(); } </script> </head> <body onload="MyOnLoad()" style="width:100%; height: 100%; padding: 0 0 0 0; margin: 0 0 0 0; overflow: hidden; background:#000000"> <div id="divScreen" style="display: block; width:100%; height="100%"> <div id="divMenu" style='float: left; background:#00FF00; border-color: #000000; border-width: 1px;'> <table> <tr> <td> Array 0/String 0: <label id="Arr00"></label> </td> </tr> <tr> <td> Array 0/String 1: <label id="Arr01"></label> </td> </tr> <tr> <td> Array 1/String 0: <label id="Arr10"></label> </td> </tr> <tr> <td> Array 1/String 1: <label id="Arr11"></label> </td> </tr> </table> </div> <div id="divMain" style='height: 100%; background:#0000FF; margin-left: 250px; border-color: #000000; border-width: 1px;'> </div> </div> </body> </html> Test.js Code: var BaseARR = function() { _arr = []; // new Array(); // Public functions that can access private members this.Add = function(arg) { var i, addAt; if(arg==null || (addAt = FindEnterPos(arg))<0) return false; // since adding and not deleting anything, nothing of value will be returned _arr.splice(addAt, 0, arg); return true; }; // This finds the entry position for in FindEnterPos = function(arg) { return (_arr.length + 1); }; this.arrayGet = function(i) { return ((_arr != null && i >= 0 && i < _arr.length) ? _arr[i] : null); }; }; var stringId = function(id, str) { // public has a this. , privates have just var this.m_Id = id; // int this.m_String = str; // string }; // This so allow statics var stringIdARR = function() { BaseARR.call(this); }; Hello, I'm taking Computer Logic in college. I only am truly familiar with HTML and CSS and minimal web hosting stuff. I REALLY want to learn how to program, however. Anyway, we are doing classes/objects and functions. I am trying to figure out how to do this exercise. She starts with having us make this page that has a form that lets you select one of three radio buttons that will change the background color of the web page, along with that there is two text boxes to put a first name and last name. Then there is a button to click which puts your full name concatenated in another box below. All of this, is done, and I pretty much THINK I understand what is going on. Here is the code that we did to get this to happen: Code: <html> <head> <title>Computer Logic in class</title> <script type="text/javascript"> var nextColor = ""; var BR = "<br />"; function setColor(newColor) { nextColor = newColor; } function changeColor() { document.body.bgColor = nextColor; } function displayName() { var firstName = document.ColorAndText.firstName.value; var lastName = document.ColorAndText.lastName.value; document.ColorAndText.fullName.value = firstName + " " + lastName; } </script> </head> <body bgcolor="red"> <form name="ColorAndText" action = ""> <input type="radio" name="colors" value="Blue" onclick="setColor(this.value)"/> Blue <br /> <input type="radio" name="colors" value="LightYellow" onclick="setColor(this.value)"/> Light Yellow <br /> <input type="radio" name="colors" value="Yellow" onclick="setColor(this.value)"/> Yellow <br /> <input type="button" name="changeButton" value="changeColor" onclick="changeColor()" /> <br /> <input type="text" name="firstName" value="First Name" size="40" /><br /> <input type="text" name="lastName" value="Last Name" size="40" /><br /> <input type="text" name="fullName" readonly="true" size="40" /><br /> <input type="button" name="displayButton" value="Display name" onclick="displayName()" /> <br /> </form> </body> </html> Okay, now, I have and can do that. Seems to make sense. Now, then, the actual program I need to make is from the following exercises: Activity 3-4 The owner of a flower shop wants you to develop a form for use on the shop's web site. The form should have a single text box for the user to enter his or her name. Under the text box should be a group of radio buttons for three different kinds of flowers: Roses, Carnations, and Daisies. Below the radio buttons should be a button labeled Request Info, with a read-only text box under it for thanking the user for requesting information. This program doesn't need any functions or onclick attributes for the graphical elements. Okay, here is the code that does that, very simple HTML. Code: <html> <head> <title>Computer Logic in class</title> <script type="text/javascript"> var nextFlower = ""; var BR = "<br />"; function setFlower(newFlower) { nextFlower = newFlower; } function displayMessage() { var firstName = document.Flowers.nameBox.value; document.Flowers.fullName.value = firstName + "," + nextFlower; } </script> </head> <body bgcolor="white"> <form name="Flowers" action = ""> <input type="text" name="nameBox" value="Namebox" size="60"><br /> <input type="radio" name="flowers" value="Roses" onclick="setFlower(this.value)"/> Roses <br /> <input type="radio" name="flowers" value="Carnations" onclick="setFlower(this.value)"/> Carnations <br /> <input type="radio" name="flowers" value="Daisies" onclick="setFlower(this.value)"/> Daisies <br /> <input type="button" name="displayButton" value="Request Info" onclick="displayMessage(this.value)" /> <br /><br /> <input type="text" name="thankyou" readonly="true" size="100" value="Thanks for using this program" /> </form> </body> </html> Okay, now is where I'm stuck. The following exercise is as follows: The flower shop owner in the previous activity wants to see where you can make the form interactive and asks you to have the form display a message in the bottom text box that includes the user's name, a comma, and the words "thank you for your inquiry about" followed by the flower name the user selected. Write a function named displayMessage() that accesses the user's name from the first text box and displays the message in the read-only text box. You also need to make the Request Info button call the displayMessage() function when it's clicked. Using Javascript, make this form active by including event triggers and functions. My teacher has said that I should be able to do this by just referencing these two previous pages of code that I have already pasted. I feel like I am missing something, that I need to be doing something and it's just not working for me. I'm actually really really stuck on this. I haven't even gotten to the second half of the exercise (where I have to have it display about what flower you select) because I cant get this function to work. What am I missing? Also, the exercise we did before these two had us make a very basic account class and object. We don't have to do that at all in this anywhere, but I do know how to do it, in case I need to make a class or something. ANY AND ALL HELP GREATLY APPRECIATED!!! I just don't know what I'm supposed to do, I can't get it to work. hi all, im on a really tight deadline with this and have been strugglign all day. (i know nothing about JS!) here's my code: Code: <script language="Javascript"> var allHTMLTags = new Array(); function fadeIn(SRC) { var allHTMLTags=document.getElementsByTagName("*"); for (i=0; i<allHTMLTags.length; i++) { if (allHTMLTags[i].className.indexOf(",") !== -1) { allHTMLTags[i].style.opacity='1'; } } } function fadeOut(SRC) { var allHTMLTags=document.getElementsByTagName("*"); for (i=0; i<allHTMLTags.length; i++) { if (allHTMLTags[i].className.indexOf(",") !== -1) { allHTMLTags[i].style.opacity='0.5'; } } } </script> <li onMouseover="fadeIn(foo)" onmouseout="fadeOut(foo)"> <div class="foo" style="opacity: 0.5;"> test 1 </div> <div class="foo bar" style="opacity: 0.5;"> test 2 </div> The idea of the above, is that when you hover over the <li> all of the divs with a class CONTAINING "foo" are given an opacity of 1. the problem is, the above script only seems to work with numbers?! E.G - class="1 2" works fine. problem is i need to use words not numbers for the classes. clearly my code is rubbish, i've bodged it together from bits and pieces of different forums. PLEASE can somebody help? the end result needs to go through and find all divs with a class CONTAINING the term specified in the <li> then give them an opacity of 1, then on mouseOut return the opacity to 0.5 im sure this is newb stuff, but thanks in advance for any help you can give! I want to have another go at Javascript. I have several books on the subject but I find that my eyesight is a major problem. Therefore I want to try an on-line solution, preferably free. I have Googled, but there are so many that I am almost dizzy with the choices. Perhaps someone could recommend one. Not too fussy visually. My knowledge is VERY basic. Frank Hello! I am trying to find a script that allows you to open multiple browser tabs and then close each of those tabs, either one by one or all at once. Does anyone know how to do this please? Thanks so much for your help. Does anyone know how to make URL links that use Javascript still work when users have Javascript disabled on their browser? The only reason I'm using JS on a URL is because my link opens a PDF file, and I'm forcing it not to cache so users have the latest version. I tried the <script><noscript> tags, but I'm not sure if I'm using it correctly, as my URL completely disappears. Below is my HTML/Javascript code: <p class="download"> <script type="text/javascript">document.write("<span style=\"text-decoration: underline;\"><a href=\"javascript:void(0);\" onclick=\"window.open( 'http://www.webchild.com.au/mediakit/Direct_Media_Kit_Web.pdf?nocache='+ Math.floor( Math.random()*11 ) );\" >The Child Magazines Media Kit</a></span> (PDF 1 MB) ");</script> <noscript><span style="text-decoration: underline;"><a href="http://www.webchild.com.au/mediakit/Direct_Media_Kit_Web.pdf" >The Child Magazines Media Kit</a></span> (PDF 1 MB)</noscript> </p> Thanks for any help, Michael Hi, I have the following code snippet: test.html ====== <script language="javascript" type="text/javascript"> var testVariable = "test"; </script> <script language="javascript" type="text/javascript" src="test.js"> </script> test.js ===== var testVariable = window.top.testVariable; In firefox, I'm able to access testvariable defined within test.html in test.js. But in chrome, test.js couldnot get the window.top.testVariable field defined in test.html. Can any one please let me know how i can make it work in chrome?. Am i missing something here?. Hi Guys, I am new at JavaScript and start to do some tutorials.What I am trying to do here is prompting user to input a name and if the name was valid the page(document) will display with all objects like the button.But if user enter a wrong name then the button will be disabled! I create the following code but it did not work <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>New Web Project</title> <script language="JavaScript" type=""> function changeColor(){ document.bgColor = "Gray"; } </script> </head> <body> <script language="JavaScript" type="text/javascript"> var person = ""; person = prompt('What is Your Name:'); if (person == "Foo") { document.write("<h1 />Welcome " + person); document.bgColor = "Yellow"; } else { document.write("<h1 />Access Denied!!!!"); document.bgColor = "Red"; document.getElementById("gree").disabled = true; } </script> <div> <p/><input id="gree" type="button" value="Gray " onClick="changeColor();"> </div> </body> </html> as you can see I used the: document.getElementById("gree").disabled = true; but it did not work , could you please give an idea how I can solve this problem? Thanks I got an index.php Code: <html> <form action="bacakomik.php" method='post'> <select name="kodekomik"> <option value='../komik1/|23'>Judul Komik1</option> <option value="../komik2/|20">Judul Komik2</option> <option value="../komik3/|10">Juduk Komik3</option> <option value="../komik4/|20">Judul Komik4</option> </select> <input type="submit" /> </form> <?php echo ('<select>'); echo ('<option value= "'.$i.'">'.'Page '.$i.'</option>'); echo ('</select>'); ?> </html> As you can see, each of the option brings specific value "../komik1/|23" komik1 is a directory | is a delimiter 23 is the pages in one chapter and can be considered also as how many images are there on a specific directory This is my bacakomik.php Code: <?php $dirkomik = $_POST['kodekomik']; $exploded = explode("|", $dirkomik); echo ($exploded[0]); //picture directory echo ("<br>"); echo ($exploded[1]); //total page in the comic $pagecount = (int)$exploded[1]; //Take last posted value, process it right away echo ('<FORM name="guideform"> '); echo ('<select name="guidelinks">'); $i=1; do { echo ('<option value= "'.$i.'">'.'Page '.$i.'</option>'); $i= $i+1; }while($i <= $pagecount); //Printing option and select echo ("</select>"); ?> <input type="button" name="go" value="Go!" onClick="document.getElementById('im').src=document.guideform.guidelinks.options[document.guideform.guidelinks.selectedIndex].value+'.png';"> </FORM> <img src="img0.jpg" id="im"> With the current code on bacakomik.php, I only can change the img src of id "im" in the same directory only. What I want is that the Javascript could "add" the "$exploded[0]" variable so that the picture can be loaded from different directory. Anyone can do this? I believe that the fix should be somewhere on input tag inside OnClick, or do you know where? Anyway, I found this on the net http://p2p.wrox.com/php-faqs/11606-q...avascript.html Please help me to those who can... Hey, I've got to make the values of some textboxes change the co-ordinates of my sprite on a canvas and havent a clue on how to do it, Here is my form with the two textboxes and submit button: <form> x: <input type="text" name="x" /><br /> y: <input type="text" name:"y" /><br /> <input type="submit" value="Submit"/><br /> </form> And i need it so that they change the values of these: //this shows where my sprite will start on the canvas var block_x; var block_y; searched the internet for hours and cant really find anything i understand or works. any help is much appreciated Hi Guys I am trying to modify the functionality of my page. I want to be able to activate this piece of code using another javascript function. This is the code I want to activate: Code: <script type="text/javascript"><!-- $('#button-cart').bind('click', function() { $.ajax({ url: 'index.php?route=checkout/cart/update', type: 'post', data: $('.product-info input[type=\'text\'], .product-info input[type=\'hidden\'], .product-info input[type=\'radio\']:checked, .product-info input[type=\'checkbox\']:checked, .product-info select, .product-info textarea, .date_data input[type=\'text\']'), dataType: 'json', success: function(json) { $('.success, .warning, .attention, information, .error').remove(); if (json['error']) { if (json['error']['warning']) { $('#notification').html('<div class="warning" style="display: none;">' + json['error']['warning'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>'); $('.warning').fadeIn('slow'); } for (i in json['error']) { $('#option-' + i).after('<span class="error">' + json['error'][i] + '</span>'); } } if (json['success']) { $('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>'); $('.success').fadeIn('slow'); $('#cart_total').html(json['total']); $('html, body').animate({ scrollTop: 0 }, 'slow'); } } }); }); //--></script> And this is how I want the format of the function to be: function testsession() { if there is a session called 'hiredate' { activate the script above } else { var el = document.getElementById("product_data"); } } I just dont know how to write this in javascript Could you help me if possible please I want to insert this js snippet Code: function addText(smiley) { document.getElementById('message').value += " " + smiley + " "; document.getElementById('message').focus(); return false; } to a loaded iframe with name&id chtifrm. I can access it & change embed something in its html via using something like: Code: $(parent.chtifrm.document.body).append('<div id=\"smly\" style=\"cursor:pointer;float:left;top:200px;display:none;position:absolute;\"><\/div>'); .... Code: parent.chtifrm.document.getElementById('chatbox_option_disco').style.display == 'none' but how do I insert js in the head of loaded iframe? All -- I have a JavaScript config file called gameSetting.js which contains a bunch of variables which configures a particular game. I also have a shared JavaScript library which uses the variables in gameSetting.js, which I include like so: <script type="text/javascript" src="gameSetting.js" ></script> <script type="text/javascript" src="gameLibrary.js" ></script> In gameSetting.js I have: $(document).ready(function() { // call some functions / classes in gameLibrary.js } in Firefox, Safari, and Chrome, this works fine. However, in IE, when it's parsing gameSetting.js, it complains that the functions that live in gameLibrary.js aren't defined. When it gets to parsing gameLibrary.js, the variables in gameSetting.js are reported as not being defined. I've tried dynamically bootstrapping the gameLibrary file using this function in document.ready for dynamic load... $.getScript("gameLibrary.js"); However, the same problem still happens in IE, where when it parses the files individually it's not taking into context the file/variables that came before, so it's not an out of load order problem. My options a 1) collapsing all the functions in gameLibrary.js and variables in gameSetting.js into one file. However, this is not practical because this is dealing with literally hundreds of games, and having a gameLibrary.js in ONE location for ONE update is what makes most logical sense. 2) figure out a way to get this to work where variables in file1 are accessible to file2 in IE (as it seems they are in other browsers). jQuery seems to be able to have multiple plugins that all refer to the based jQuery-1.3.2.js, so I know there is a way to get this to work. Help appreciated. Nero |