Prevent screen from moving when clicking on <a href=></a> - html

I'm using <a href> element along with :target css selector to show a <div> which by default is set to display:none. Problem is, that when I click on the link to show that <div>, it is automatically scrolling down my site towards that <div>.
Is there a way to stop the screen movement?
Unfortunately I am not yet proficient in anything besides CSS and HTML.

You can use event.preventDefault() to avoid this. Something like this:
$('a.yourclass').click(function(e)
{
//your code
e.preventDefault();
});
OR:
link

in the link enter:
Link here

You'll need JS anyway:
// (in jQuery)
$el.on('click', function(e) {
// find current scroll position
var pos = document.body.scrollTop || document.documentElement.scrollTop;
// let normal action propagate etc
// in the next available frame (async, hence setTimeout), reset scroll posiion
setTimeout(function() {
window.scrollTo(0, pos);
}, 1);
})
I don't know if this will flicker the screen. It might. It's a horrible hack either way.
In my Chrome, there's no flicker: http://jsfiddle.net/rudiedirkx/LEwNd/1/show/

There are two ways to tell the browser we don't want it to act:
The main way is to use the event object. There's a method
event.preventDefault().
If the handler is assigned using on (not by
addEventListener), then we can just return false from it.
Example:
Click here
or
here

This is a bit of a hack but you could use a basic css work around:
CSS only Example
#div1 {
height: 0;
overflow:hidden;
}
#div1:target {
height: auto;
margin-top: -110px;
padding-top: 110px;
}
#div2 {
background:red;
}
Click to show
<div id="div1">
<div id="div2">Content</div>
</div>
If you need it to be a little more flexible you can add some js...
More Flexible Example with JS
$('a').click(function () {
$('#div1').css({
'margin-top': 0 - $('#div1').position().top + $(window).scrollTop(),
'padding-top': $('#div1').position().top - $(window).scrollTop()
});
});
Basically you're pulling the top of div1 up with the negative margin and then pushing div2 back down with the padding, so that the top of div1 rests at the top of the window... Like I said its a hack but it does the trick.

Those links are anchor-links and by default made for those jumps :) You could use JS to prevent the default behaviour in some way. For example using jQuery:
$('a').click(function(e){e.preventDefault();});
or by default add return false; to the links

Avoid using :target all together and just use onclick event.
function myFunction()
{
document.getElementById('hiddenDiv').style.display = 'block';
return false;
}

Related

Sometimes links are not clickable [duplicate]

I have a link button inside a <td> which I have to disable. This works on IE but not working in Firefox and Chrome.
I tried all the following but not working on Firefox (using 1.4.2 js):
$(".myLink").attr('disabled', 'disabled');
$(".myLink").attr('disabled', true);
$(".myLink").attr('disabled', 'true');
Note - I cannot de-register the click function for the anchor tag as it is registered dynamically. AND I HAVE TO SHOW THE LINK IN DISABLED MODE.
You can't disable a link (in a portable way). You can use one of these techniques (each one with its own benefits and disadvantages).
CSS way
This should be the right way (but see later) to do it when most of browsers will support it:
a.disabled {
pointer-events: none;
}
It's what, for example, Bootstrap 3.x does. Currently (2016) it's well supported only by Chrome, FireFox and Opera (19+). Internet Explorer started to support this from version 11 but not for links however it's available in an outer element like:
span.disable-links {
pointer-events: none;
}
With:
<span class="disable-links">...</span>
Workaround
We, probably, need to define a CSS class for pointer-events: none but what if we reuse the disabled attribute instead of a CSS class? Strictly speaking disabled is not supported for <a> but browsers won't complain for unknown attributes. Using the disabled attribute IE will ignore pointer-events but it will honor IE specific disabled attribute; other CSS compliant browsers will ignore unknown disabled attribute and honor pointer-events. Easier to write than to explain:
a[disabled] {
pointer-events: none;
}
Another option for IE 11 is to set display of link elements to block or inline-block:
<a style="pointer-events: none; display: inline-block;" href="#">...</a>
Note that this may be a portable solution if you need to support IE (and you can change your HTML) but...
All this said please note that pointer-events disables only...pointer events. Links will still be navigable through keyboard then you also need to apply one of the other techniques described here.
Focus
In conjunction with above described CSS technique you may use tabindex in a non-standard way to prevent an element to be focused:
...
I never checked its compatibility with many browsers then you may want to test it by yourself before using this. It has the advantage to work without JavaScript. Unfortunately (but obviously) tabindex cannot be changed from CSS.
Intercept clicks
Use a href to a JavaScript function, check for the condition (or the disabled attribute itself) and do nothing in case.
$("td > a").on("click", function(event){
if ($(this).is("[disabled]")) {
event.preventDefault();
}
});
To disable links do this:
$("td > a").attr("disabled", "disabled");
To re-enable them:
$("td > a").removeAttr("disabled");
If you want instead of .is("[disabled]") you may use .attr("disabled") != undefined (jQuery 1.6+ will always return undefined when the attribute is not set) but is() is much more clear (thanks to Dave Stewart for this tip). Please note here I'm using the disabled attribute in a non-standard way, if you care about this then replace attribute with a class and replace .is("[disabled]") with .hasClass("disabled") (adding and removing with addClass() and removeClass()).
Zoltán Tamási noted in a comment that "in some cases the click event is already bound to some "real" function (for example using knockoutjs) In that case the event handler ordering can cause some troubles. Hence I implemented disabled links by binding a return false handler to the link's touchstart, mousedown and keydown events. It has some drawbacks (it will prevent touch scrolling started on the link)" but handling keyboard events also has the benefit to prevent keyboard navigation.
Note that if href isn't cleared it's possible for the user to manually visit that page.
Clear the link
Clear the href attribute. With this code you do not add an event handler but you change the link itself. Use this code to disable links:
$("td > a").each(function() {
this.data("href", this.attr("href"))
.attr("href", "javascript:void(0)")
.attr("disabled", "disabled");
});
And this one to re-enable them:
$("td > a").each(function() {
this.attr("href", this.data("href")).removeAttr("disabled");
});
Personally I do not like this solution very much (if you do not have to do more with disabled links) but it may be more compatible because of various way to follow a link.
Fake click handler
Add/remove an onclick function where you return false, link won't be followed. To disable links:
$("td > a").attr("disabled", "disabled").on("click", function() {
return false;
});
To re-enable them:
$("td > a").removeAttr("disabled").off("click");
I do not think there is a reason to prefer this solution instead of the first one.
Styling
Styling is even more simple, whatever solution you're using to disable the link we did add a disabled attribute so you can use following CSS rule:
a[disabled] {
color: gray;
}
If you're using a class instead of attribute:
a.disabled {
color: gray;
}
If you're using an UI framework you may see that disabled links aren't styled properly. Bootstrap 3.x, for example, handles this scenario and button is correctly styled both with disabled attribute and with .disabled class. If, instead, you're clearing the link (or using one of the others JavaScript techniques) you must also handle styling because an <a> without href is still painted as enabled.
Accessible Rich Internet Applications (ARIA)
Do not forget to also include an attribute aria-disabled="true" together with disabled attribute/class.
Got the fix in css.
td.disabledAnchor a{
pointer-events: none !important;
cursor: default;
color:Gray;
}
Above css when applied to the anchor tag will disable the click event.
For details checkout this link
Thanks to everyone that posted solutions (especially #AdrianoRepetti), I combined multiple approaches to provide some more advanced disabled functionality (and it works cross browser). The code is below (both ES2015 and coffeescript based on your preference).
This provides for multiple levels of defense so that Anchors marked as disable actually behave as such.
Using this approach, you get an anchor that you cannot:
click
tab to and hit return
tabbing to it will move focus to the next focusable element
it is aware if the anchor is subsequently enabled
How to
Include this css, as it is the first line of defense. This assumes the selector you use is a.disabled
a.disabled {
pointer-events: none;
cursor: default;
}
Next, instantiate this class on ready (with optional selector):
new AnchorDisabler()
ES2015 Class
npm install -S key.js
import {Key, Keycodes} from 'key.js'
export default class AnchorDisabler {
constructor (config = { selector: 'a.disabled' }) {
this.config = config
$(this.config.selector)
.click((ev) => this.onClick(ev))
.keyup((ev) => this.onKeyup(ev))
.focus((ev) => this.onFocus(ev))
}
isStillDisabled (ev) {
// since disabled can be a class or an attribute, and it can be dynamically removed, always recheck on a watched event
let target = $(ev.target)
if (target.hasClass('disabled') || target.prop('disabled') == 'disabled') {
return true
}
else {
return false
}
}
onFocus (ev) {
// if an attempt is made to focus on a disabled element, just move it along to the next focusable one.
if (!this.isStillDisabled(ev)) {
return
}
let focusables = $(':focusable')
if (!focusables) {
return
}
let current = focusables.index(ev.target)
let next = null
if (focusables.eq(current + 1).length) {
next = focusables.eq(current + 1)
} else {
next = focusables.eq(0)
}
if (next) {
next.focus()
}
}
onClick (ev) {
// disabled could be dynamically removed
if (!this.isStillDisabled(ev)) {
return
}
ev.preventDefault()
return false
}
onKeyup (ev) {
// We are only interested in disabling Enter so get out fast
if (Key.isNot(ev, Keycodes.ENTER)) {
return
}
// disabled could be dynamically removed
if (!this.isStillDisabled(ev)) {
return
}
ev.preventDefault()
return false
}
}
Coffescript class:
class AnchorDisabler
constructor: (selector = 'a.disabled') ->
$(selector).click(#onClick).keyup(#onKeyup).focus(#onFocus)
isStillDisabled: (ev) =>
### since disabled can be a class or an attribute, and it can be dynamically removed, always recheck on a watched event ###
target = $(ev.target)
return true if target.hasClass('disabled')
return true if target.attr('disabled') is 'disabled'
return false
onFocus: (ev) =>
### if an attempt is made to focus on a disabled element, just move it along to the next focusable one. ###
return unless #isStillDisabled(ev)
focusables = $(':focusable')
return unless focusables
current = focusables.index(ev.target)
next = (if focusables.eq(current + 1).length then focusables.eq(current + 1) else focusables.eq(0))
next.focus() if next
onClick: (ev) =>
# disabled could be dynamically removed
return unless #isStillDisabled(ev)
ev.preventDefault()
return false
onKeyup: (ev) =>
# 13 is the js key code for Enter, we are only interested in disabling that so get out fast
code = ev.keyCode or ev.which
return unless code is 13
# disabled could be dynamically removed
return unless #isStillDisabled(ev)
ev.preventDefault()
return false
Try the element:
$(td).find('a').attr('disabled', 'disabled');
Disabling a link works for me in Chrome: http://jsfiddle.net/KeesCBakker/LGYpz/.
Firefox doesn't seem to play nice. This example works:
<a id="a1" href="http://www.google.com">Google 1</a>
<a id="a2" href="http://www.google.com">Google 2</a>
$('#a1').attr('disabled', 'disabled');
$(document).on('click', 'a', function(e) {
if ($(this).attr('disabled') == 'disabled') {
e.preventDefault();
}
});
Note: added a 'live' statement for future disabled / enabled links.
Note2: changed 'live' into 'on'.
Bootstrap 4.1 provides a class named disabled and aria-disabled="true" attribute.
example"
<a href="#"
class="btn btn-primary btn-lg disabled"
tabindex="-1"
role="button" aria-disabled="true"
>
Primary link
</a>
More is on getbootstrap.com
So if you want to make it dynamically, and you don't want to care if it is button or ancor than
in JS script you need something like that
let $btn=$('.myClass');
$btn.attr('disabled', true);
if ($btn[0].tagName == 'A'){
$btn.off();
$btn.addClass('disabled');
$btn.attr('aria-disabled', true);
}
But be carefull
The solution only works on links with classes btn btn-link.
Sometimes bootstrap recommends using card-link class, in this case solution will not work.
Just add a css property:
<style>
a {
pointer-events: none;
}
</style>
Doing so you can disable the anchor tag.
I've ended up with the solution below, which can work with either an attribute, <a href="..." disabled="disabled">, or a class <a href="..." class="disabled">:
CSS Styles:
a[disabled=disabled], a.disabled {
color: gray;
cursor: default;
}
a[disabled=disabled]:hover, a.disabled:hover {
text-decoration: none;
}
Javascript (in jQuery ready):
$("a[disabled], a.disabled").on("click", function(e){
var $this = $(this);
if ($this.is("[disabled=disabled]") || $this.hasClass("disabled"))
e.preventDefault();
})
In Razor (.cshtml) you can do:
#{
var isDisabled = true;
}
Home
You can disable the HTML link as given below:
<style>
.disabled-link {
pointer-events: none;
}
</style>
Google.com
You can use inline JavaScript:
Google.com
you cannot disable a link, if you want that click event should not fire then simply Remove the action from that link.
$(td).find('a').attr('href', '');
For More Info :- Elements that can be Disabled
I would do something like
$('td').find('a').each(function(){
$(this).addClass('disabled-link');
});
$('.disabled-link').on('click', false);
something like this should work. You add a class for links you want to have disabled and then you return false when someone click them. To enable them just remove the class.
To disable link to access another page on touch device:
if (control == false)
document.getElementById('id_link').setAttribute('href', '#');
else
document.getElementById('id_link').setAttribute('href', 'page/link.html');
end if;
I would suggest turning the link into a button and using the 'disabled' attribute. You can see this issue to check how to convert a link to a button: How to create an HTML button that acts like a link
You can use this to disabled the Hyperlink of asp.net or link buttons in html.
$("td > a").attr("disabled", "disabled").on("click", function() {
return false;
});
There is one other possible way, and the one that I like best. Basically it's the same way lightbox disables a whole page, by placing a div and fiddling with z-index. Here is relevant snippets from a project of mine. This works in all browsers!!!!!
Javascript (jQuery):
var windowResizer = function(){
var offset = $('#back').offset();
var buttontop = offset.top;
var buttonleft = offset.left;
$('#backdisabler').css({'top':buttontop,'left':buttonleft,'visibility':'visible'});
offset = $('#next').offset();
buttontop = offset.top;
buttonleft = offset.left;
$('#nextdisabler').css({'top':buttontop,'left':buttonleft,'visibility':'visible'});
}
$(document).ready(function() {
$(window).resize(function() {
setTimeout(function() {
windowResizer();
}, 5); //when the maximize/restore buttons are pressed, we have to wait or it will fire to fast
});
});
and in html
<img src="images/icons/back.png" style="height: 50px; width: 50px" />
<img src="images/icons/next.png" style="height: 50px; width: 50px" />
<img id="backdisabler" src="images/icons/disabled.png" style="visibility: hidden; position: absolute; padding: 5px; height: 62px; width: 62px; z-index: 9000"/>
<img id="nextdisabler" src="images/icons/disabled.png" style="visibility: hidden; position: absolute; padding: 5px; height: 62px; width: 62px; z-index: 9000"/>
So the resizer finds the anchor's (the images are just arrows) locations and places the disabler on top. The disabler's image is a translucent grey square (change the width/height of the disablers in the html to match your link) to show that it is disabled. The floating allows the page to resize dynamically, and the disablers will follow suit in windowResizer(). You can find suitable images through google. I have placed the relevant css inline for simplicity.
then based on some condition,
$('#backdisabler').css({'visibility':'hidden'});
$('#nextdisabler').css({'visibility':'visible'});
I think a lot of these are over thinking. Add a class of whatever you want, like disabled_link. Then make the css have .disabled_link { display: none }
Boom now the user can't see the link so you won't have to worry about them clicking it. If they do something to satisfy the link being clickable, simply remove the class with jQuery: $("a.disabled_link").removeClass("super_disabled"). Boom done!

how to make a js textarea draggable

I have a textarea generated with the bellow js code, I also have a button that creates additional text areas when clicked, I NEED to make each text area draggable, Ussually because the "id" is "myForm" it should become draggable using jquery $('#myForm') but it does not work, I have try all forms but it does not work. I also have check similar questions but not luck... I will appreciate if some one can help me out. in the folder I have the Html, The css and all jquery libraries working Ok.
I check with the alert box.
Note: all I need is a textarea with a button to add as many additional text areas and this areas to be draggable, the code to generate this text areas can be any code. In case there is a easier way to accomplish the same thing... Thank you in advance.
function myFunction() {
var x = document.createElement("FORM");
x.setAttribute("id", "myForm");
document.body.appendChild(x);
var y = document.createElement("TEXTAREA");
document.getElementById("myForm").appendChild(y);
}
Is HTML5 Drag and Drop what you are looking for?
All you need to do is define draggable=true in your element and code the relevant ondragstart and ondragend logic. This works with both vanilla JS and frameworks like React.
Made for you kindly however dosn't work in this editor
var new_offset = {top:30, left:40};
var new_width = 200;
var new_height = 150;
var newElement$ = $('<div><textarea id="textarea"></textarea></div>')
.width(new_width)
.height(new_height)
.draggable({
cancel: "text",
start: function (){
$('#textarea').focus();
},
stop: function (){
$('#textarea').focus();
}
})
.resizable()
.css({
'position' : 'absolute',
'background-color' : 'gray',
'border-color' : 'black',
'border-width' : '1px',
'border-style' : 'solid'
})
.offset(new_offset)
.appendTo('body');
textarea {
height:100%;
background-color:whit;
width:100%;
resize:none; border:none;
padding:0px; margin:0px;
}
div { padding:0px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
I hacked it and piggy tailed to a span element this way the span element is easy to make draggable with jquery, The textarea is not draggable but it has to follow the span element THUS is draggable.
The span element has the class= "drag",then I used the jquery $('.drag').draggable and that made the whole trick. Dirty code BUT it works 100% the way I needed.

"document.getElementbyId" isn't working for me

I have a button in my page
<button onclick="document.getElementById('donation').style.visibility='visible'">Support</button>
That I want to have linked to making a hidden div (donation) visible. I'm not sure if the getElementById works with divs, but I couldn't find out either, because when I changed the Id to h1, with a simple color change for style, it didn't work either.
Is there a problem with my button or syntax?
You can still work this with an inline onclick.
Andrei is correct about the id needing to be an individual.
<button onclick="document.getElementById('donation').style.visibility='visible'">Support</button>
<div style="background-color: gray; width: 50px; height: 50px; visibility: hidden;" id="donation"></div>
Technically though, it's better to keep your css and javascript in the head tag or outside of the html.
In order for document.getElementById('donation') to return a DOM element this condition would need to be true
there should be one html element and only one with id="donation" in your page. For example: <div id="donation"></div>
It's possible that your function works flawlessly (you can easily tell if it is by looking at your browser console after you pushed the button) but your element would still remain not visible. For example, if its display property is set to none. There are many possible reasons why an element might not be rendered by the browser. The fastest way to pinpoint the reason would be for you to create a minimal, complete and verifiable example (using the <> button) where we could experience the issue.
For me, I think separating the codes will keep things clearer and readable.
<button id="donation_btn">Support</button>
The javascript
function enableDonation( button, donationElement ) {
// check if the button is defined
if ( button != undefined
&& button != null ) {
button.addEventListener( "click", function () {
donationElement.style.display = "block";
});
}
// execute the code on document load
window.addEventListener( "load", function () {
enableDonation(
document.getElementById( "donation_btn" ),
document.getElementById( "donation" )
);
});

Go to last div added inside div [duplicate]

I am creating a chat using Ajax requests and I'm trying to get messages div to scroll to the bottom without much luck.
I am wrapping everything in this div:
#scroll {
height:400px;
overflow:scroll;
}
Is there a way to keep it scrolled to the bottom by default using JS?
Is there a way to keep it scrolled to the bottom after an ajax request?
Here's what I use on my site:
var objDiv = document.getElementById("your_div");
objDiv.scrollTop = objDiv.scrollHeight;
This is much easier if you're using jQuery scrollTop:
$("#mydiv").scrollTop($("#mydiv")[0].scrollHeight);
Try the code below:
const scrollToBottom = (id) => {
const element = document.getElementById(id);
element.scrollTop = element.scrollHeight;
}
You can also use Jquery to make the scroll smooth:
const scrollSmoothlyToBottom = (id) => {
const element = $(`#${id}`);
element.animate({
scrollTop: element.prop("scrollHeight")
}, 500);
}
Here is the demo
Here's how it works:
Ref: scrollTop, scrollHeight, clientHeight
using jQuery animate:
$('#DebugContainer').stop().animate({
scrollTop: $('#DebugContainer')[0].scrollHeight
}, 800);
Newer method that works on all current browsers:
this.scrollIntoView(false);
var mydiv = $("#scroll");
mydiv.scrollTop(mydiv.prop("scrollHeight"));
Works from jQuery 1.6
https://api.jquery.com/scrollTop/
http://api.jquery.com/prop/
alternative solution
function scrollToBottom(element) {
element.scroll({ top: element.scrollHeight, behavior: 'smooth' });
}
smooth scroll with Javascript:
document.getElementById('messages').scrollIntoView({ behavior: 'smooth', block: 'end' });
If you don't want to rely on scrollHeight, the following code helps:
$('#scroll').scrollTop(1000000);
Java Script:
document.getElementById('messages').scrollIntoView(false);
Scrolls to the last line of the content present.
My Scenario: I had an list of string, in which I had to append a string given by a user and scroll to the end of the list automatically. I had fixed height of the display of the list, after which it should overflow.
I tried #Jeremy Ruten's answer, it worked, but it was scrolling to the (n-1)th element. If anybody is facing this type of issue, you can use setTimeOut() method workaround. You need to modify the code to below:
setTimeout(() => {
var objDiv = document.getElementById('div_id');
objDiv.scrollTop = objDiv.scrollHeight
}, 0)
Here is the StcakBlitz link I have created which shows the problem and its solution : https://stackblitz.com/edit/angular-ivy-x9esw8
If your project targets modern browsers, you can now use CSS Scroll Snap to control the scrolling behavior, such as keeping any dynamically generated element at the bottom.
.wrapper > div {
background-color: white;
border-radius: 5px;
padding: 5px 10px;
text-align: center;
font-family: system-ui, sans-serif;
}
.wrapper {
display: flex;
padding: 5px;
background-color: #ccc;
border-radius: 5px;
flex-direction: column;
gap: 5px;
margin: 10px;
max-height: 150px;
/* Control snap from here */
overflow-y: auto;
overscroll-behavior-y: contain;
scroll-snap-type: y mandatory;
}
.wrapper > div:last-child {
scroll-snap-align: start;
}
<div class="wrapper">
<div>01</div>
<div>02</div>
<div>03</div>
<div>04</div>
<div>05</div>
<div>06</div>
<div>07</div>
<div>08</div>
<div>09</div>
<div>10</div>
</div>
You can use the HTML DOM scrollIntoView Method like this:
var element = document.getElementById("scroll");
element.scrollIntoView();
Javascript or jquery:
var scroll = document.getElementById('messages');
scroll.scrollTop = scroll.scrollHeight;
scroll.animate({scrollTop: scroll.scrollHeight});
Css:
.messages
{
height: 100%;
overflow: auto;
}
Using jQuery, scrollTop is used to set the vertical position of scollbar for any given element. there is also a nice jquery scrollTo plugin used to scroll with animation and different options (demos)
var myDiv = $("#div_id").get(0);
myDiv.scrollTop = myDiv.scrollHeight;
if you want to use jQuery's animate method to add animation while scrolling down, check the following snippet:
var myDiv = $("#div_id").get(0);
myDiv.animate({
scrollTop: myDiv.scrollHeight
}, 500);
I have encountered the same problem, but with an additional constraint: I had no control over the code that appended new elements to the scroll container. None of the examples I found here allowed me to do just that. Here is the solution I ended up with .
It uses Mutation Observers (https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) which makes it usable only on modern browsers (though polyfills exist)
So basically the code does just that :
var scrollContainer = document.getElementById("myId");
// Define the Mutation Observer
var observer = new MutationObserver(function(mutations) {
// Compute sum of the heights of added Nodes
var newNodesHeight = mutations.reduce(function(sum, mutation) {
return sum + [].slice.call(mutation.addedNodes)
.map(function (node) { return node.scrollHeight || 0; })
.reduce(function(sum, height) {return sum + height});
}, 0);
// Scroll to bottom if it was already scrolled to bottom
if (scrollContainer.clientHeight + scrollContainer.scrollTop + newNodesHeight + 10 >= scrollContainer.scrollHeight) {
scrollContainer.scrollTop = scrollContainer.scrollHeight;
}
});
// Observe the DOM Element
observer.observe(scrollContainer, {childList: true});
I made a fiddle to demonstrate the concept :
https://jsfiddle.net/j17r4bnk/
Found this really helpful, thank you.
For the Angular 1.X folks out there:
angular.module('myApp').controller('myController', ['$scope', '$document',
function($scope, $document) {
var overflowScrollElement = $document[0].getElementById('your_overflow_scroll_div');
overflowScrollElement[0].scrollTop = overflowScrollElement[0].scrollHeight;
}
]);
Just because the wrapping in jQuery elements versus HTML DOM elements gets a little confusing with angular.
Also for a chat application, I found making this assignment after your chats were loaded to be useful, you also might need to slap on short timeout as well.
Like you, I'm building a chat app and want the most recent message to scroll into view. This ultimately worked well for me:
//get the div that contains all the messages
let div = document.getElementById('message-container');
//make the last element (a message) to scroll into view, smoothly!
div.lastElementChild.scrollIntoView({ behavior: 'smooth' });
small addendum: scrolls only, if last line is already visible. if scrolled a tiny bit, leaves the content where it is (attention: not tested with different font sizes. this may need some adjustments inside ">= comparison"):
var objDiv = document.getElementById(id);
var doScroll=objDiv.scrollTop>=(objDiv.scrollHeight-objDiv.clientHeight);
// add new content to div
$('#' + id ).append("new line at end<br>"); // this is jquery!
// doScroll is true, if we the bottom line is already visible
if( doScroll) objDiv.scrollTop = objDiv.scrollHeight;
Just as a bonus snippet. I'm using angular and was trying to scroll a message thread to the bottom when a user selected different conversations with users. In order to make sure that the scroll works after the new data had been loaded into the div with the ng-repeat for messages, just wrap the scroll snippet in a timeout.
$timeout(function(){
var messageThread = document.getElementById('message-thread-div-id');
messageThread.scrollTop = messageThread.scrollHeight;
},0)
That will make sure that the scroll event is fired after the data has been inserted into the DOM.
This will let you scroll all the way down regards the document height
$('html, body').animate({scrollTop:$(document).height()}, 1000);
You can also, using jQuery, attach an animation to html,body of the document via:
$("html,body").animate({scrollTop:$("#div-id")[0].offsetTop}, 1000);
which will result in a smooth scroll to the top of the div with id "div-id".
Scroll to the last element inside the div:
myDiv.scrollTop = myDiv.lastChild.offsetTop
You can use the Element.scrollTo() method.
It can be animated using the built-in browser/OS animation, so it's super smooth.
function scrollToBottom() {
const scrollContainer = document.getElementById('container');
scrollContainer.scrollTo({
top: scrollContainer.scrollHeight,
left: 0,
behavior: 'smooth'
});
}
// initialize dummy content
const scrollContainer = document.getElementById('container');
const numCards = 100;
let contentInnerHtml = '';
for (let i=0; i<numCards; i++) {
contentInnerHtml += `<div class="card mb-2"><div class="card-body">Card ${i + 1}</div></div>`;
}
scrollContainer.innerHTML = contentInnerHtml;
.overflow-y-scroll {
overflow-y: scroll;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="d-flex flex-column vh-100">
<div id="container" class="overflow-y-scroll flex-grow-1"></div>
<div>
<button class="btn btn-primary" onclick="scrollToBottom()">Scroll to bottom</button>
</div>
</div>
Css only:
.scroll-container {
overflow-anchor: none;
}
Makes it so the scroll bar doesn't stay anchored to the top when a child element is added. For example, when new message is added at the bottom of chat, scroll chat to new message.
Why not use simple CSS to do this?
The trick is to use display: flex; and flex-direction: column-reverse;
Here is a working example. https://codepen.io/jimbol/pen/YVJzBg
A very simple method to this is to set the scroll to to the height of the div.
var myDiv = document.getElementById("myDiv");
window.scrollTo(0, myDiv.innerHeight);
On my Angular 6 application I just did this:
postMessage() {
// post functions here
let history = document.getElementById('history')
let interval
interval = setInterval(function() {
history.scrollTop = history.scrollHeight
clearInterval(interval)
}, 1)
}
The clearInterval(interval) function will stop the timer to allow manual scroll top / bottom.
I know this is an old question, but none of these solutions worked out for me. I ended up using offset().top to get the desired results. Here's what I used to gently scroll the screen down to the last message in my chat application:
$("#html, body").stop().animate({
scrollTop: $("#last-message").offset().top
}, 2000);
I hope this helps someone else.
I use the difference between the Y coordinate of the first item div and the Y coordinate of the selected item div. Here is the JavaScript/JQuery code and the html:
function scrollTo(event){
// In my proof of concept, I had a few <button>s with value
// attributes containing strings with id selector expressions
// like "#item1".
let selectItem = $($(event.target).attr('value'));
let selectedDivTop = selectItem.offset().top;
let scrollingDiv = selectItem.parent();
let firstItem = scrollingDiv.children('div').first();
let firstItemTop = firstItem.offset().top;
let newScrollValue = selectedDivTop - firstItemTop;
scrollingDiv.scrollTop(newScrollValue);
}
<div id="scrolling" style="height: 2rem; overflow-y: scroll">
<div id="item1">One</div>
<div id="item2">Two</div>
<div id="item3">Three</div>
<div id="item4">Four</div>
<div id="item5">Five</div>
</div>

HTML/CSS: Show full size image on click

I have a text + image side by side, and I want a function where the user can click on the image to make it bigger. I'm new to HTML/CSS so I was wondering how I can approach this. Thanks! (demo -> https://jsfiddle.net/DTcHh/6634/)
Is there any way to do this with pure HTML/CSS and no javascript?
The ones I found have been telling me to use javascript such as:
<script type="text/javascript">
function showImage(imgName) {
document.getElementById('largeImg').src = imgName;
showLargeImagePanel();
unselectAll();
}
function showLargeImagePanel() {
document.getElementById('largeImgPanel').style.visibility = 'visible';
}
function unselectAll() {
if(document.selection) document.selection.empty();
if(window.getSelection) window.getSelection().removeAllRanges();
}
function hideMe(obj) {
obj.style.visibility = 'hidden';
}
</script>
Is there a simpler way to do this in HTML/CSS?
You could use a CSS pseudo-class to change the styling when, for example, the mouse is over the image:
img:hover {
width: 300px;
height: 300px;
}
Generally, though, to add interactivity to your web pages, you will have to become acquainted with JavaScript. I don't know of any way to toggle a state (e.g. "zoomed-in") without the use of JavaScript.
You can think of the HTML as defining the content, the CSS as defining how it looks, and the JavaScript as defining how it behaves.