I have been trying to make jquery scroll text in a textbox using a button click but it does not work in IE, Chrome, or Firefox.
I would like my textbox manually to scroll down on click of the button.
<!DOCTYPE html>
<html>
<head>
<script src="http://localhost:62240/Scripts/jquery-2.1.1.js"></script>
<script>
x = 0;
$(document).ready(function () {
$("div").scroll(function () {
$("span").text(x += 1);
});
$("button").click(function () {
$("div").scroll();
});
});
</script>
</head>
<body>
<p>Try the scrollbar in the div</p>
<div style="border:1px solid black;width:200px;height:100px;overflow:scroll;">
In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
<br><br>
'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.'
</div>
<p>Scrolled <span>0</span> times.</p>
<button>Trigger scroll event for the window</button>
</body>
</html>
scroll() is the event fired when div is scrolled. If you want to scroll by clicking on the button, try this instead:
x = 0;
$(document).ready(function () {
$("button").click(function () {
$('div').animate({ scrollTop: (x+1)*20 }, 200);
$("span").text(x += 1);
});
});
Your jquery import doesn't work. If you take the exact same code, paste it into a jsfiddle with jquery imported by them, and then click the button, the span counter increments.
This is the code from @lpg fixed to make everything work properly(sorry I write this as an answer, I don't have enough reputation to comment yet):
x = 0;
height = 0;
$(document).ready(function () {
$("button").click(function () {
height = $('div').scrollTop();
$('div').animate({ scrollTop: height+20 }, 200);
});
$('div').scroll(function() {
$("span").text(x += 1);
});
});
Here is the JS Fiddle demo fixed.
The jQuery method element.scrollTop();
is used to get the scroll position of a scrollable element, and also to set it when an argument is included. Then $('div').scrollTop();
returns the pixels scrolled inside the div from its top, and $('div').scrollTop(20);
will scroll the div 20 pixels from its top.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.