auto-resizing text input box html - javascript

I created an input (type text) box and made it auto-resize quite simply. However, there are a few glitches that I can't seem to fix:
when I start typing the box shrinks a tiny bit
when I press backspace (or directional arrows), the box expands first, and then shrinks when I continue typing.
Here is my code:
function Expander() {
this.start = function () {
$("#inputbox").keydown(function(e) {
this.style.width = 0;
var newWidth = this.scrollWidth + 10;
if( this.scrollWidth >= this.clientWidth )
newWidth += 10;
this.style.width = newWidth + 'px';
});
}
}
$(function() {
window.app = new Expander();
window.app.start();
});
input {
margin-left:3em;
min-width:100px;
max-width:600px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<meta charset="UTF-8">
<body>
<div id="wrap">
<input type="text" id="inputbox" name="input" placeholder="I want this to resize smoothly." width="100px"/>
</div>
<div id="counter"></div>
</body>

You can try this.
We put the content in a hidden span & then adjust width according to span scrollWidth.
function Expander() {
this.start = function () {
$('#inputbox').on('keydown',function(e) {
$("#hidden_span").html("");
$("#hidden_span").append("<p>"+$(this).val()+"</p>");
var hidden_span_scroll_width=$("#hidden_span")[0].scrollWidth;
if(hidden_span_scroll_width> 100||hidden_span_scroll_width< 600){
$(this).css("width",hidden_span_scroll_width);
}
});
}
}
$(function() {
window.app = new Expander();
window.app.start();
});
input {
margin-left:3em;
min-width:100px;
max-width:600px;
}
#hidden_span{
position:absolute;
top:0px;
left:0px;
visibility:hidden;
width:10px;
white-space:nowrap;
overflow:hidden;
}
<head>
<meta charset="UTF-8">
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
</head>
<body>
<div id="wrap">
<input type="text" id="inputbox" name="input" placeholder="I want this to resize smoothly." />
</div>
<div id="counter"></div>
<span id="hidden_span"></span>
</body>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<title>Test page</title>
</head>
<body>
<style>
input {
margin-left:3em;
min-width:100px;
max-width:600px;
}
#hidden_span{
position:absolute;
top:0px;
left:0px;
visibility:hidden;
width:10px;
white-space:nowrap;
overflow:hidden;
}
</style>
<script>
function Expander() {
this.start = function () {
$('#inputbox').on('keydown',function(e) {
$("#hidden_span").html("");
$("#hidden_span").append("<p>"+$(this).val()+"</p>");
var hidden_span_scroll_width=$("#hidden_span")[0].scrollWidth;
if(hidden_span_scroll_width> 100||hidden_span_scroll_width< 600){
$(this).css("width",hidden_span_scroll_width);
}
});
}
}
$(function() {
window.app = new Expander();
window.app.start();
});
</script>
<div id="wrap">
<input type="text" id="inputbox" name="input" placeholder="yes" />
</div>
<div id="counter"></div>
<span id="hidden_span"></span>
</body>
</html>

At first you can use jQuery methods to avoid crossbrowser problem. And scrollWidth returns either the width in pixels of the content of an element or the width of the element itself, whichever is greater. So enlarge newWidth only when content width strongly larger than element width.
$("#inputbox").keydown(function(e) {
var a = $(this).width(), newWidth;
if(this.scrollWidth - a > 0){
newWidth = a + 10;
}else if(e.keyCode==8){
newWidth = a - 10;
}
$(this).css("width", newWidth);
});
If you don't want to make input smaller when pressed backspace - delete else if part of code.

<input type="text" id="inputbox" name="input" placeholder="yes" width="100px"/>
Remove the width="100px", like this:
<input type="text" id="inputbox" name="input" placeholder="yes"/>
And it won't resize down anymore when starting to type.
Live example:
http://jsfiddle.net/2EMfd/
Though, the exanding function doesn't seem to work in my browser?
*Edit, did a simple expand function on the inputbox is this what you where trying? http://jsfiddle.net/2EMfd/1/

Related

Add two text fields together that include commas and decimals with JavaScript only

In order to add a feature to a existing application I'm attempting to use JavaScript to add together input fields which need to stay as text field types and show the end result text field as a total of those fields. I can easily make it work adding the numbers together. However the numbers will be typed in with commas and decimals every time. When this happens the adding breaks and doesn't work. Anyone have any ideas of how I could possibly make this work?
HTML CODE
<form method="post">
<input type="text" id="the_input_id">
<input type="text" id="the_input_id1">
<input type="text" id="total">
JavaScript
$(function() {
$('#the_input_id').keyup(function() {
updateTotal();
});
$('#the_input_id1').keyup(function() {
updateTotal();
});
var updateTotal = function () {
var input1 = parseInt($('#the_input_id').val());
var input2 = parseInt($('#the_input_id1').val());
if (isNaN(input1) || isNaN(input2)) {
if(!input2){
$('#total').val($('#the_input_id').val());
}
if(!input1){
$('#total').val($('#the_input_id1').val());
}
} else {
$('#total').val(input1 + input2);
}
};
var output_total = $('#total');
var total = input1 + input2;
output_total.val(total);
});
How about something like this?
var num1 = "1,000,000.00"
var num2 = "1,000,000.25"
var re = /,/gi;
var num1a = num1.replace(re,''); // strip commas
var num2a = num2.replace(re, ''); // strip commas
var sum = Number(num1a) + Number(num2a); // convert to Number and add together
console.log(sum); // before formatting
var total = Number(sum).toLocaleString(); // formatted
console.log(total)
Read my comment above, then take a look here:
//<![CDATA[
/* js/external.js */
$(function(){
var num1 = $('#num1'), num2 = $('#num2'), total = $('#total'); // why get them again unless they're dynamic ?
function updateTotal(){
var s = num1.val().replace(/,/g, ''), s2 = num2.val().replace(/,/g, '');
if(s === '' && s2 === ''){
total.text('Awaiting Input').addClass('er');
}
else if(isNaN(s) && isNaN(s2)){
total.text('Numbers Required').addClass('er');
}
else if(s === ''){
total.text('Awaiting First Number').addClass('er');
}
else if(isNaN(s)){
total.text('First Input Requires Number').addClass('er');
}
else if(s2 === ''){
total.text('Awaiting Second Number').addClass('er')
}
else if(isNaN(s2)){
total.text('Second Input Requires Number').addClass('er');
}
else{
total.text(((+s)+(+s2)).toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2})).removeClass('er');
}
};
num1.keyup(updateTotal); num2.keyup(updateTotal);
}); // end jQuery load
//]]>
/* css/external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
html,body{
width:100%; height:100%;
}
body{
background:#ccc;
}
#content{
padding:7px;
}
input[type=text]{
width:100px; padding:0 3px;
}
.er{
color:#900;
}
#total{
display:inline-block;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
<title>Test Template</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script type='text/javascript' src='js/external.js'></script>
</head>
<body>
<div id='content'>
<input type='text' id='num1' /> &plus;
<input type='text' id='num2' /> &equals;
<div class='er' id='total'>Awaiting Input</div>
</div>
</body>
</html>
Note that you can use + in front of a String to cast it to a number... and that JavaScript has a Floating Point Number Math issue.
Here is a <form> example:
//<![CDATA[
/* js/external.js */
$(function(){
var form = $('#form'), num1 = $('#num1'), num2 = $('#num2'), total = $('#total'); // why get them again unless they're dynamic ?
function updateTotal(){
var s = num1.val().replace(/,/g, ''), s2 = num2.val().replace(/,/g, '');
if(s === '' && s2 === ''){
total.val('Awaiting Input').addClass('er');
}
else if(isNaN(s) && isNaN(s2)){
total.val('Numbers Required').addClass('er');
}
else if(s === ''){
total.val('Awaiting First Number').addClass('er');
}
else if(isNaN(s)){
total.val('First Input Requires Number').addClass('er');
}
else if(s2 === ''){
total.val('Awaiting Second Number').addClass('er')
}
else if(isNaN(s2)){
total.val('Second Input Requires Number').addClass('er');
}
else{
total.val(((+s)+(+s2)).toLocaleString(undefined, {minimumFractionDigits:2, maximumFractionDigits:2})).removeClass('er');
}
};
form.submit(function(e){
console.log(form.serialize());
// run a bunch of tests using if conditions and the like before AJAXing - $.post example shown
/*
$.post('sendToPage.php', form.serialize(), function(jsonResult){
// should get echo json_encode($objOrAssocArray); from PHP as jsonResult now
}, 'json');
*/
// prevents old school submission
e.preventDefault();
});
num1.keyup(updateTotal); num2.keyup(updateTotal);
}); // end jQuery load
//]]>
/* css/external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
html,body{
width:100%; height:100%;
}
body{
background:#ccc;
}
#content{
padding:7px;
}
input[type=text]{
width:100px; padding:3px 5px;
}
.symbol{
display:inline-block; width:18px; text-align:center;
}
.er{
color:#900;
}
#total{
width:calc(100% - 236px);
}
input[type=submit]{
width:100%; height:30px; background:#007; color:#fff; border:0; border-radius:5px; margin-top:4px; cursor:pointer;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
<title>Test Template</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script type='text/javascript' src='js/external.js'></script>
</head>
<body>
<div id='content'>
<form id='form'>
<input type='text' id='num1' name='num1' /><div class='symbol'>&plus;</div><input type='text' id='num2' name='num2' /><div class='symbol'>&equals;</div><input type='text' class='er' id='total' name='total' value='Awaiting Input' readonly='readonly' />
<input type='submit' id='sub' value='Submit Test' />
</form>
</div>
</body>
</html>
Maybe something like this by simply extracting only numbers from any string the user inputs:
$(function () {
var $firstInput = $('#first');
var $secondInput = $('#second');
var $totalInput = $('#total')
$firstInput.keyup(updateTotal);
$secondInput.keyup(updateTotal);
function extractNumbers(str, def) {
var onlyNumbers = '';
for (var i = 0; i < str.length; ++i) {
var currChar = str.charAt(i);
if (!isNaN(currChar)) {
onlyNumbers += currChar;
}
}
return parseInt(onlyNumbers) || def;
}
function updateTotal () {
var valInput1 = extractNumbers($firstInput.val(), 0)
var valInput2 = extractNumbers($secondInput.val(), 0)
var total = valInput1 + valInput2;
$totalInput.val(total);
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Test</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<input type="text" placeholder="first number..." id="first">
<input type="text" placeholder="second number..." id="second">
<input type="text" placeholder="total number..." id="total">
</body>
</html>

jQuery set fontsize on change of value Strange behaviour

I am trying to change the font size of a paragraph using jQuery and Angular js.
Whenever user changes the font size the p tags font size will be changed,
it's working fine. But there's a small bug i.e whenever user sets the value the font size changes But if he decrease it , it doesn't decrease but increase, and vice versa and many these type of similar behaviour occur.
This is my code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<style>
p{
height: 600px;
width: 600px;
font-size:17px;
}
</style>
</head>
<body>
<div ng-app="myApp" ng-controller="editor">
<label for="kys_font_size"> font size:</label>
<select ng-model="kys_selected_font" id="fontsize" name="kys_font_size" ng-options="page for page in FontSize(1, 150)">
</select>
</div>
<p contenteditable="true" id="content" >
</p>
<p></p>
<script>
var app = angular.module('myApp',[]);
app.controller('editor',function($scope){
$scope.FontSize = function(start, end) {
var size = [];
for (var i = start; i <= end; i++) {
size.push(i);
}
return size;
};
$("#fontsize").on('change',function(){
$("#content").css("fontSize",$scope.kys_selected_font+"px");
});
});
</script>
</body>
</html>
Its working...
you have to use ng-change...
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<style>
p{
height: 600px;
width: 600px;
font-size:17px;
}
</style>
</head>
<body>
<div ng-app="myApp" ng-controller="editor">
<label for="kys_font_size"> font size:</label>
<select ng-model="kys_selected_font" id="fontsize" name="kys_font_size" ng-options="page for page in FontSize(1, 150)" ng-change="update()">
</select>
</div>
<p contenteditable="true" id="content" >
</p>
<p></p>
<script>
var app = angular.module('myApp',[]);
app.controller('editor',function($scope){
$scope.FontSize = function(start, end) {
var size = [];
for (var i = start; i <= end; i++) {
size.push(i);
}
return size;
};
$scope.update = function(){
$("#content").css("fontSize",$scope.kys_selected_font+"px");
}
});
</script>
</body>
</html>

change alert message text color using javascript

Am using the below script to change the color of the script but showing 'font color="red">Hello world /font> like this.Is any possible way to change the alert text color..
<html>
<head>
<title>JavaScript String fontcolor() Method</title>
</head>
<body>
<script type="text/javascript">
var str = new String("Hello world");
alert(str.fontcolor( "red" ));
</script>
</body>
</html>
No. alert() accepts a string and renders it using a native widget. There is no provision to style it.
The closest you could get would be to modify the HTML document via the DOM to display the message instead of using an alert().
You can use JQuery to resolve your Problem
<html>
<head>
<meta charset="utf-8" />
<title>JavaScript String fontcolor() Method</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery- ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#dialog-message" ).dialog({
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}});
});
</script>
</head>
<body>
<div id="dialog-message" title="My Dialog Alternative">
<p style='color:red'> Hello world </p>
</div>
</body>
</html>
Hope this help :
<!doctype html>
<html>
<head>
<title>JavaScript String fontcolor() Method</title>
<style>
#alertoverlay{display: none;
opacity: .8;
position: fixed;
top: 0px;
left: 0px;
background: #FFF;
width: 100%;}
#alertbox{display: none;
position: fixed;
background: #000;
border:7px dotted #12f200;
border-radius:10px;
font-size:20px;}
#alertbox > div > #alertboxhead{background:#222; padding:10px;color:#FFF;}
#alertbox > div > #alertboxbody{ background:#111; padding:40px;color:red; }
#alertbox > div > #alertboxfoot{ background: #111; padding:10px; text-align:right; }
</style><!-- remove padding for normal text alert -->
<script>
function CustomAlert(){
this.on = function(alert){
var winW = window.innerWidth;
var winH = window.innerHeight;
alertoverlay.style.display = "block";
alertoverlay.style.height = window.innerHeight+"px";
alertbox.style.left = (window.innerWidth/3.5)+"pt";
alertbox.style.right = (window.innerWidth/3.5)+"pt"; // remove this if you don't want to have your alertbox to have a standard size but after you remove modify this line : alertbox.style.left=(window.inner.Width/4);
alertbox.style.top = (window.innerHeight/10)+"pt";
alertbox.style.display = "block";
document.getElementById('alertboxhead').innerHTML = "JavaScript String fontcolor() Method :";
document.getElementById('alertboxbody').innerHTML = alert;
document.getElementById('alertboxfoot').innerHTML = '<button onclick="Alert.off()">OK</button>';
}
this.off = function(){
document.getElementById('alertbox').style.display = "none";
document.getElementById('alertoverlay').style.display = "none";
}
}
var Alert = new CustomAlert();
</script>
</head>
<body bgcolor="black">
<div id="alertoverlay"></div>
<div id="alertbox">
<div>
<div id="alertboxhead"></div>
<div id="alertboxbody"></div>
<div id="alertboxfoot"></div>
</div>
</div>
<script>Alert.on("Hello World!");</script>
</body>
</html>
The concept is taken from this : http://www.developphp.com/video/JavaScript/Custom-Alert-Box-Programming-Tutorial

How to stop animation with jQuery timers?

I'm wondering how to stop an animation made with jQuery timers. I think I have tried everything, I would really like your help.
<!DOCTYPE html>
<html>
<head>
<meta content='yes' name='apple-mobile-web-app-capable'>
<meta content='default' name='apple-mobile-web-app-status-bar-style'>
<meta content='width=device-width, minimum-scale=1.0, maximum-scale=1.0' name='viewport'>
<title>HeartMath - Danmark</title>
<script src='http://code.jquery.com/jquery.min.js' type='text/javascript'></script>
<script src='http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js' type='text/javascript'></script>
<script src='inc/jquery.timers-1.1.2.js' type='text/javascript'></script>
<script type="text/javascript" >
jQuery.fn.log = function (msg) {
console.log("%s: %o", msg, this);
return this;
}; var fixgeometry = function() {
/* Some orientation changes leave the scroll position at something
* that isn't 0,0. This is annoying for user experience. */
scroll(0, 0);
/* Calculate the geometry that our content area should take */
var header = $(".header:visible");
var footer = $(".footer:visible");
var content = $(".content:visible");
var viewport_height = $(window).height();
var content_height = viewport_height - header.outerHeight() - footer.outerHeight();;
/* Trim margin/border/padding height */
content_height -= (content.outerHeight() - content.height());
content.height(content_height);
}; /* fixgeometry */
$(document).ready(function() {
$(window).bind("orientationchange resize pageshow", fixgeometry);
var animationSpeed = 3500;
var animationHeight = $(window).height() * 0.70;
$("input[type='radio']").bind( "change", function(event, ui) {
if($(this).val() == "true") {
startAnimation(animationSpeed);
$(this).log("animationen burde starte");
}
else {
stopAnimation();
$(this).log("animationen burde stopppe");
}
}).log("der blev trykket");
function startAnimation(animationDuration) {
$(".breather").everyTime(10, function(){
$(".breather").animate({top:animationHeight}, animationDuration).animate({top:"0"}, animationDuration);
}).log("startAnimation");
};
function stopAnimation() {
$(".breather").stopTime().stop().log("stopAnimation");
};
});
</script>
<style type="text/css">
html, body {
width: 100%;
}
div.breather {
display: block;
position:relative;
}
}
</style>
<link href='http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.min.css' rel='stylesheet'>
<link rel="stylesheet" type="text/css" href="jquery-mobile/hm-mobile-theme.css">
</head>
<body>
<div data-role='page' data-theme='a'>
<div class='header' id="header" data-role='header'> <img src="img/hm-logo.png" style="margin:0px auto;" height="40" /> </div>
<div class='content' data-role='content'>
<div class="breather">landscape!</div>
</div>
<div class='footer' data-role='footer'>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal">
<input type="radio" name="ignition" id="start" value="true" />
<label for="start">Start</label>
<input type="radio" name="ignition" id="stop" value="false" checked="checked" />
<label for="stop">Stop</label>
</fieldset>
</div>
</div>
</div>
</body>
</html>
What happens now is that when i press stop.. the animation just reverses and loops again
When you call .stop() to stop the jQuery animation, change it to .stop(true) to clear the animation queue (docs here). I'm not sure why there is a queue, but it looks like it has something to do with the timers plugin that you are using. Use queue().length to see how many animations are left in the queue.
Please make sure that the stopAnimation is being called by adding some debugging (console.log()). You call stopAnimation without an argument, but the function has an argument, that's not used.
So add some debugging to stopanimation and the if(val==false) statement. If that all works as expected we can continue the search.

Slide div inside another div effect

I am trying to create sliding images effect:
Online demolink text.
The problem is when you click rapidly and randomly on the buttons and not wait for animation to finish causing unpredicted results and even stopping the functionality to work. (and once it stopped in the middle of 2 images...)
How Can I make it work without bugs?
I know that there are some other tools for that sliding like jquery and other approaches like changing the position attribute and not the scrollLeft attribute.
But I want to do it as it is, with scrollLeft, if it possible of course.
The Code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<style type="text/css">
body
{
padding:0px;
margin:0px;
}
#imageContainer
{
width: 500px;
position: relative;
}
#div
{
overflow: hidden;
white-space: nowrap;
}
#div img {
cursor: pointer;
vertical-align: bottom;
width: 500px;
padding:0px;
margin:0px;
display:inline;
}
</style>
<script type="text/javascript">
var scrollIntervalID;
var currentIndex=0;
function Scroll(ind){
var dir = ind ==currentIndex?0:ind<currentIndex?-1:1;
var steps = Math.abs(ind-currentIndex);
scrollIntervalID = setInterval(function(){
var i=(steps*10)-1;
return function(){
if (i <= 0)
clearInterval(scrollIntervalID);
var elm = document.getElementById("div");
elm.scrollLeft +=dir * 50;
i--;
document.getElementById("span").innerHTML=elm.scrollLeft;
}
}(), 15);
currentIndex=ind;
}
</script>
</head>
<body>
<div id="imageContainer">
<div id="div">
<img id="image1" src="Images/pic1.jpg" width="500px"/><img id="image2" src="Images/pic2.jpg" width="500px"/><img id="image3" src="Images/pic3.jpg" width="500px"/><img id="image4" src="Images/pic4.jpg" width="500px"/>
</div>
</div>
<div>
<input type="button" value="1" onclick="Scroll(0);"/>
<input type="button" value="2" onclick="Scroll(1);"/>
<input type="button" value="3" onclick="Scroll(2);"/>
<input type="button" value="4" onclick="Scroll(3);"/>
</div>
<span id="span"></span>
</body>
</html>
I would sriously recommend you to use frameworks like jQuery but if you insist to work on the current version, you have to take care of scenarios which happens during the animation.
You have scrollIntervalID, but it is not used outside the scope of the function. You can try clearing the interval timer by using clearInterval when a previous sliding animation is in progress and advance the position to the intended one before performing the next animation.
You need to stop the previous animation from operating before starting a new one. At the beginning, set:
var scrollIntervalID= null;
Then at the start of function Scroll add:
if (scrollIntervalID!==null) {
clearInterval(scrollIntervalID);
scrollIntervalID= null;
}
You'll also want to base the starting position of the animation on the current value of scrollLeft, rather than trying to remember the currentIndex.
this is a quick fix, I am not a javascript expert. but it works based on my quick testing
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<style type="text/css">
body
{
padding:0px;
margin:0px;
}
#imageContainer
{
width: 500px;
position: relative;
}
#div
{
overflow: hidden;
white-space: nowrap;
}
#div img {
cursor: pointer;
vertical-align: bottom;
width: 500px;
padding:0px;
margin:0px;
display:inline;
}
</style>
<script type="text/javascript">
var scrollIntervalID;
var currentIndex=0;
var start = true;
function Scroll(ind){
if(start){
var dir = ind ==currentIndex?0:ind<currentIndex?-1:1;
var steps = Math.abs(ind-currentIndex);
scrollIntervalID = setInterval(function(){
start = false;
var i=(steps*10)-1;
return function(){
if (i <= 0)
clearInterval(scrollIntervalID);
var elm = document.getElementById("div");
elm.scrollLeft +=dir * 50;
i--;
document.getElementById("span").innerHTML=elm.scrollLeft;
}
}(), 0);
currentIndex=ind;
start = true;
}
}
</script>
</head>
<body>
<div id="imageContainer">
<div id="div">
<img id="image1" src="Images/pic1.jpg" width="500px"/><img id="image2" src="Images/pic2.jpg" width="500px"/><img id="image3" src="Images/pic3.jpg" width="500px"/><img id="image4" src="Images/pic4.jpg" width="500px"/>
</div>
</div>
<div>
<input type="button" value="1" onclick="Scroll(0);"/>
<input type="button" value="2" onclick="Scroll(1);"/>
<input type="button" value="3" onclick="Scroll(2);"/>
<input type="button" value="4" onclick="Scroll(3);"/>
</div>
<span id="span"></span>
</body>

Categories