Fast help with javascript

Discussion in 'Web Programming' started by AfterLyfe, Aug 27, 2012.

Fast help with javascript
  1. Unread #1 - Aug 27, 2012 at 9:43 AM
  2. AfterLyfe
    Joined:
    Sep 23, 2010
    Posts:
    391
    Referrals:
    0
    Sythe Gold:
    0

    AfterLyfe Forum Addict

    Fast help with javascript

    Code:
    onload = init;
    
    function init(){
    	document.getElementsByTagName("h2")[0].onclick = function(){changeit("chan1", "background");};	
    	document.getElementsByTagName("h2")[1].onclick = function(){changeit("chan1", "typecolor");};	
    	document.getElementsByTagName("h2")[2].onclick = function(){changeit("chan1", "minimize");};	
    	document.getElementsByTagName("h2")[3].onclick = function(){changeit("chan1", "increase");};	
    	document.getElementsByTagName("h2")[4].onclick = function(){changeit("chan1", "visibility");};	
    	document.getElementsByTagName("h2")[5].onclick = function(){changeit("chan1", "move");};	
    }
    
    function changeit(id, classStyle){
    		if(document.getElementById(id).className == classStyle)
    		{
    			document.getElementById(id).className= "";
    		} else {
    			document.getElementById(id).className += " " + classStyle;
    		} 
    
    }		
    
    I am trying to create a object that will switch between classes, and hold the property of the last class at the same time. The problem is I can not find a way to make it remove a class that is used after another class is added.

    I am pretty new to javascript so all help is greatly appreciated :)
     
  3. Unread #2 - Aug 27, 2012 at 7:50 PM
  4. Jazz00006
    Joined:
    Aug 26, 2005
    Posts:
    807
    Referrals:
    0
    Sythe Gold:
    0

    Jazz00006 Apprentice
    Visual Basic Programmers

    Fast help with javascript

    Is vanilla JS needed?
    Have you looked at jQuery?

    It makes things a lot easier :)
    Code:
    $('#btn').removeClass('btn-danger')
    			.removeClass('btn-warning')
    			.addClass('btn-primary');

    Otherwise you can try a replace
    Code:
    document.getElementById("MyElement").className.replace( /(?:^|\s)MyClass(?!\S)/g , '' )
    You may also want to learn some basic regex, or atleast understand s/asd/ASD/g http://gskinner.com/RegExr/
     
< Web site design / coding | Help? >

Users viewing this thread
1 guest


 
 
Adblock breaks this site