Click here to Skip to main content
15,113,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to move text on button click. Please help me I am not able to do this.
Posted

1 solution

The way I usually use is to make sure the text is in a div that has it's position set to absolute. Once the div has this style, you can position it by setting the left and top attributes of the element's style.

Here, I've wrapped a button and some text in a div. Clicking the button calls a handler. The handler is supplied with the element that was clicked. Inside the handler, the clicked object's parent is determined. From there, the left and top of the parent element (the div) are set to random values.

The 'shift-right zero places' code makes sure the values are integers.
intValue = floatValue >> 0;

HTML
<!doctype html>
<html>
<head>
<style>
#tgtDiv
{
	border: solid 1px red;
	background-color: #ccc;
	display: inline-block;
	position: absolute;
}
</style>
<script>
function onBtnClick(clickedElement)
{
	var btnObj = clickedElement;
	var parentDiv = btnObj.parentNode;
	
	parentDiv.style.left = ((Math.random() * 320) >> 0) + "px";
	parentDiv.style.top = ((Math.random() * 200) >> 0) + "px";
}

</script>
</head>
<body>
	<div id='tgtDiv'>
		Click button to move to random position
		<button onclick='onBtnClick(this);'>Ok</button>
	</div>
</body>
</html>
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900