JavaScript - Switching Between Two Css Classes Via Onclick
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! Similar TutorialsI want to create the form button similar to this: http://www.customusb.com/quoteform-wref-flashdrives.php Im a designer and i m a total noob in javascript, would appreciate very much if you could be patient with me.... i use an OnClick to switch the image but the if else statement just doent let me switch back to the original image, i not sure where i have gone wrong... appreciate again if anyone could help me out... below are the html and js thumnails: http://img215.imageshack.us/f/73258715.jpg/ http://img35.imageshack.us/f/44225148.jpg/ Hi, I have two versions of a script: version A gets used on a visitor's first round, where the page is dynamically altered; if the visitor wants to do another round, I need to switch to version B. I could load both versions initially, but that seems overkill. Any suggestions ? 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> Hi Forum, to develop a "Digital Signage" applikation we need: 1) After loading the (main) html page get all the pages (.html, .pdf, .xls, .jpg) as members of the paylist. - Is there a way to get the appr. 15 pages into the browser (as DOM Objects) ? Or rather to load in 15 iFrames ? 2) The mentionde pages should be displayed in a certain order (in ca. 20 sec tact). - A possible solution would be to hide / unhide. Any other wy ? Thanks in advance Michel So I had the orginial code just switch images, I was under the impression I could use "var clientData" to make an array. However this is not working out the way I had hoped. Any help or explanation, greatly appreciated. It's very sloppy now! Don't judge. Here is my Javascript: Code: <script type="text/javascript"> var imgList = [ "../Assets/Images_Revised/40_kitchen.jpg", "../Assets/Images_Revised/40_stair.jpg", "../Assets/Images_Revised/C_front2.jpg", "../Assets/Images_Revised/C_rear_side_combo.jpg", "../Assets/Images_Revised/C_side.jpg", "../Assets/Images_Revised/Y_combo.jpg", "../Assets/Images_Revised/Y_window.jpg" ]; var clientData = [ "This is Data for Client 1"; "This is Data for Client 2"; "This is Data for Client 3"; "This is Data for Client 4"; "This is Data for Client 5"; "This is Data for Client 6"; "This is Data for Client 7" ]; var currentMain = 0; var currentMainT = 0; function Prev() { return ShowMain(currentMain-1); return ShowMainT(currentMainT-1); } function Next() { return ShowMain(currentMain+1); return ShowMainT(currentMainT+1); } function ShowMain(which) { currentMain = which; currentMainT = which; if ( currentMain < 0 ) currentMain = 0; if ( currentMainT < 0 ) currentMainT = 0; if ( currentMain > imgList.length-1) currentMain = imgList.length-1; if ( currentMainT > clientData.length-1) currentMainT = clientData.length-1; document.getElementById('mainImg').src = imgList[currentMain]; document.getElementById('mainText').src = clientData[currentMainT]; var PD = document.getElementById('Pg'); var PD2 = document.getElementById('Pg2'); if (PD != null ) PD.innerHTML = 'Image '+(currentMain+1)+' of '+imgList.length; if (PD2 != null ) PD2.innerHTML = (currentMainT+1)+' of '+clientData.length; return false; } onload = function() { ShowMain(0); } onload = function() { ShowMainT(0); } </script> Here is my area I am showing it. Code: <a href="#" onclick="return ShowMain(0); return ShowMainT(0)">1</a ><a href="#" onclick="return ShowMain(1); return ShowMainT(1);">2</a ><a href="#" onclick="return ShowMain(2); return ShowMainT(2)">3</a ><a href="#" onclick="return ShowMain(3); return ShowMainT(3)">4</a ><a href="#" onclick="return ShowMain(4); return ShowMainT(4)">5</a ><a href="#" onclick="return ShowMain(5); return ShowMainT(5)">6</a ><a href="#" onclick="return ShowMain(6); return ShowMainT(6)">7</a ><a href="#" onclick="return Prev();" class="gallery"><</a ><a href="#" class="gallery" onclick="return Next();">></a> <span id="mainText">Click on a Client for Information.</span> Hi, I am relatively new to JavaScript and I am trying to write a script to switch style sheets when a user clicks a button. I got my script to work. I created buttons with in the script, put them in a div, and used appendChild to add the div to the page. This all works and the style sheets switch, however I want to add a cookie, so when the user returns to the page it displays with the style sheet they were using last. I can't figure out how to grab which style sheet the user selected, to add it to the cookie. I have included the code for the switching. Code: function addEvent(object, evName, fnName, cap) { if (object.attachEvent) object.attachEvent("on" + evName, fnName); else if (object.addEventListener) object.addEventListener(evName, fnName, cap); } addEvent(window, "load", makeStyleButton, false); var allStyles = new Array(); function makeStyleButton() { var allLinks = document.getElementsByTagName("link"); for(var i = 0; i<allLinks.length; i++) { if((allLinks[i].rel == "stylesheet" || allLinks[i].rel == "alternate stylesheet") && allLinks[i].rel.title !="") { allStyles.push(allLinks[i]); } } var styleBox = document.createElement("div"); for(var i =0; i<allStyles.length; i++) { if(allStyles[i].rel == "stylesheet") { allStyles[i].disabled = false; } else { allStyles[i].disabled = true; } styleButton = document.createElement("input"); styleButton.type = "button"; styleButton.value = allStyles[i].title + " view"; styleButton.title = allStyles[i].title; styleButton.style.width = "125px"; styleButton.style.fontSize = "12px"; styleButton.onclick = changeStyle; styleBox.appendChild(styleButton); } styleBox.style.width = "125px"; styleBox.style.cssFloat = "right"; styleBox.style.styleFloat = "right"; styleBox.style.margin = "5px 5px 10px 10px"; var sourceDoc = document.getElementById("content"); sourceDoc.insertBefore(styleBox, sourceDoc.firstChild); } function changeStyle() { for(var i = 0; i<allStyles.length; i++) { if (allStyles[i].title == this.title) { allStyles[i].disabled = false; } else { allStyles[i].disabled = true; } } } I am not looking for someone to give me the answer, I am just looking for a push in the right direction, so to speak. I seem to be going around in circles with this problem. Thank you for your time. I have a site where i switch between two images using some JavaScript. What I need is to be able to set a session variable or something so that if someone selects shading on or off it sticks to that for the rest of the session. Any idea or even a point in the right direction. Do i need cookies or is there a simple way to do this http://www.tech4t.co.uk/territorymapping/pentagon/ As a newbie, I've been combining scripts and adjusting them to create a page that allows viewers to choose from different visual elements of a leaf that will be used to search a database. There are rollovers for each anchor dropdown, and a center image that is in layers to "assemble" the leaf. But I've run into a logistical nightmare and I'm not sure which is the best way to handle this. if variations were slight, i would have no problem. But to show some characteristics I need to know what one or two underlying images were as well. In other words, if I am choosing borders, and I have a round image. The border would have to know to put a round scalloped border - not a square one. (And if somebody goes back to change the shape, I would need the border to automatically know to change to a square scalloped border) Can I build conditionals within the layers? Or does it need to be inline with the image? is there another way to do this before my script becomes a disaster when I try to accommodate for numerous variations. Can I get a snippet or two of code to send me in the right direction? maybe there's some precreated script for this? (I can dream!) I hope that makes some sense. Here's the page that I'm working on. http://www.mergecreate.com/test25n.html I have a banner that has image navigation on the lower right. The navigation links are images which, when clicked, change the banner without reloading the page. The actual switching of the banner is working when each image is clicked. However, my problem is this: The page itself is long and must be vertically-scrolled to see the entire content. Because of the scrolling, the banner could appear anywhere vertically on the page. And whenever I click the banner navigation hrefs, the page "jumps" so that the banner is at the top. The page should really stay in the fixed position. I'm not sure how to set it up so that no matter where the banner section is on the scrolled page, that the page stays in the same position when the navigation is clicked. My href's in that navigation are set up as : <a href="#"></a> Do I need something in my script so that the page won't jump? Or am I missing something in the HTML? Hi, I looked around to see javascript codes on websites but had no luck in finding what I wanted... or I just don't know how to work with it I want to switch/replace image with other images by clicking on radio buttons. i have the html, but how can I make this work??? can anyone help me out? Code: <body> <p><img name="main" src="black.jpg" width="100" height="100" alt=""></p> <p> <input type="radio" name="red" id="radio" value="radio" onClick="display red in main image"> </p> <p> <input type="radio" name="blue" id="radio2" value="radio" onClick="display blue in main image"> </p> <p> <input type="radio" name="green" id="radio3" value="radio" onClick="display green in main image"> </p> <p> <input type="radio" name="yellow" id="radio4" value="radio" onClick="display yellow in main image"> </p> <p> <input type="radio" name="black" id="radio5" value="radio" onClick="this would this play the main image 'black'.jpg"> </p> </body> thanks for any help in advance! I'm trying to allow the user to change the stylesheet of my website. I can change the stylesheet on a page by page basis (eg. from red style to blue style) but once the user navigates to a different page the stylesheet resets back to the original setting. For example, when the user visits the site first its set to the red style, they can change it to blue but when they navigate to another page the style goes back to red again where as I want the style to stick across pages. Does anybody know how I can sort this out? I assume I'll have to edit my javascript but Im not very good at javascript so any help would be great! HTML Code: <html> <head> <link href="red.css" rel="stylesheet" type="text/css" title="red" media="screen" /> <link href="green.css" rel="alternate stylesheet" type="text/css" title="green" media="screen" /> <link href="blue.css" rel="alternate stylesheet" type="text/css" title="blue" media="screen" /> <script type="text/javascript"> function changeStyle(title) { var lnks = document.getElementsByTagName('link'); for (var i = lnks.length - 1; i >= 0; i--) { if (lnks[i].getAttribute('rel').indexOf('style')> -1 && lnks[i].getAttribute('title')) { lnks[i].disabled = true; if (lnks[i].getAttribute('title') == title) lnks[i].disabled = false; }}} </script> </head> <body> <a href = "home1.html">Page 1</a> <br> <br> <a href = "home2.html">Page 2</a> <br> <br> <a href = "home3.html">Page 3</a> <br> <br> <br> <br> <a href = "#" onclick="changeStyle('red')">Red Stylesheet</a> <br> <br> <a href = "#" onclick="changeStyle('blue')">Blue Stylesheet</a> <br> <br> <a href = "#" onclick="changeStyle('green')">Green Stylesheet</a> </body> </html> CSS Code: body { background-color:red; } There are two pages, folder/india.html folder/usa.html and dropdown menu in each page to switch between india and usa pages. india.html page sells in INR and usa.html in USD with links to shopping carts for each currency. link1(INR) link2(USD) Except the link and the currency information(selling price), contents in both the pages are same. So here comes the problem. Google hates duplicate pages! I am looking for a solution where, a single page In That Page, a dropdown menu to select currency As the currency is selected, without page reload, the link to shopping cart and the pricing also should be changed according to the selected currency. So Single page should be able to handle both the currencies. Kindly suggest me with codes as I am new to javascript. Thanks a lot Heres a link to the code in question http://www.scccs.ca/~W0049698/JavaTe...erlocktxt.htm# when the leftPos variable is used in the moveSlide() it somehow turns into Nan. Cant figure out why and have been racking my brain over this for a long time now.. Any help would be greatly appreciated the problem is at the end of the code(scroll to the bottom) ======================================================= Code: window.onload = makeMenus; var currentSlide = null; var timeID = null; function makeMenus(){ var slideMenus = new Array(); var allElems = document.getElementsByTagName("*"); for(var i=0 ; i < allElems.length ; i++){ if(allElems[i].className == "slideMenu") slideMenus.push(allElems[i]) } for(var i=0 ; i < slideMenus.length ; i++){ // alert(slideMenus.length) slideMenus[i].onclick = showSlide; slideMenus[i].getElementsByTagName("ul")[0].style.left = "0px"; } document.getElementById("head").onClick = closeSlide; document.getElementById("main").onClick = closeSlide; } function showSlide(){ slideList = this.getElementsByTagName("ul")[0]; if(currentSlide && currentSlide.id == slideList.id) {closeSlide()} else{ closeSlide(); currentSlide = slideList; currentSlide.style.display = "block"; timeID = setInterval("moveSlide()", 1); } } function closeSlide(){ if(currentSlide){ clearInterval(timeID); currentSlide.style.left="0px"; currentSlide.style.display="none"; currenSlide = null; } } Code: I'm currently working on a project and I am doing a bunch of image switching. I'm having a problem with the following... I have seven medium image objects and one small one. One is at the top and the other 7 are below. When one of the 7 is clicked, it then becomes the one up top and the one up top then takes the place of the image clicked. This needs to be able to happen no matter which of the seven i click. Also when you click one of the seven it runs a script to change 9 other images in the center of the page. this isnt too important because i have it working already. What i have is, each of the seven images run their function that changes the 9 center images and then it runs another function. What i need is for that function to determine which company for example(shaws, lowes, target) the top image belongs to and replace the image that was clicked with the top one. But i also need to replace the NAME="" and ONCLICK="function()" with the proper ones for the original company up top. Please if you can understand what im trying to do let me know, if you need further clarification i can do so. i can draw a picture of what im trying to do or the layout if needed but i cant necessarily show anyone the project due to a non-disclosure. Is it possible disable an onclick after clicking it and then enable it from another onclick by id Code: <img id="one" href="images/homepage/sliders/bonus_button.jpg" style="position:relative; top:30px; left:50px; height:30px; width:70px; float:left;"> This code runs when it is clicked: Code: $("#one").click(function() { runEffectB(); return false; }); What I would like to happen is for either runEffectB() to not run if it was just run or to disable the #one.click once it has run. I am assuming I will be able to re-enable it from another onclick running a similar function. This is jquery and jquery ui if that helps. Any ideas much appreciated. 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? Hi 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, 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. 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 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); }; |