0

Hi!
I´m completely new at javascript, and I got a little issue.

I want to be able to have some text in my index-page and 2 buttons to change this text back and forth with diffrent text.

Say i have one headline like this

<div id="first">
<h1>Hello world</h1>
<p>Lorem ipsum etc............</p>
</div>

and i want 2 buttons under this text beeing able to swap all this code for say this:

<div id="second">
<h1>Hello president</h1>
<p>Lorem ipsum etc............</p>
</div>


and most likely sevral more swaps, so the buttons would work like a library function.

Thanks in advance...

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by Airshow
0

Hwestman,

There are many ways to formulate this, eg. :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Airshow :: Untitled</title>
<style type="text/css">
button.headline {
  margin-right: 3px;
}
</style>

<script>
onload = function(){
	var headlines = [];//new Array
	var headlineButtons = document.getElementById('headlineButtons');
	var showHeadline = function(x){
		for(var i=0; i<headlines.length; i++){
			headlines[i].style.display = (x===i) ? 'block' : 'none';
		}
	};
	var showHeadline_closure = function(x){
		return function(){ showHeadline(x); }
	}
	var divs = document.getElementsByTagName('div');
	for(var i=0; i<divs.length; i++ ){
		if(divs[i].className==='headline'){
			headlines.push(divs[i]);
			var button = document.createElement('button');
			headlineButtons.appendChild(button);
			button.className = 'headline';
			button.innerHTML = divs[i].firstChild.innerHTML;
//			button.innerHTML = 'Headline ' + i; //alternative button text
			button.onclick = showHeadline_closure(i);
		}
		showHeadline(0);
	}
};

</script>
</head>

<body>

<div id="headline1" class="headline"><h1>Hello world</h1>
<p>Lorem1 ipsum1 etc. ...........</p>
</div>

<div id="headline2" class="headline"><h1>Hello president</h1>
<p>Lorem2 ipsum2 etc. ...........</p>
</div>

<div id="headlineButtons"></div>

</body>
</html>

Before someone else says it, yes the code would be more concise by using jQuery.

Airshow

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.