JavaScript - Switching From One Class To Another
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> Similar TutorialsHi, 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 ? 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 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! 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> 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 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 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'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; } 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! 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: Hello, 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 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. 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? |