Can't override jquery mobile - html

if i specify data-role="page" on a div it adds a element.style min-height. I only need it to be on a specific height because on android emulator it overflows. I've tried adding a !important on the css side but still nothing works. help?

I know this post is old but in case anyone is wondering how to do this...
Use javascript to override the min-height style on the page
I set my min-height to the window height.
$( "#mypanelright" ).on( "panelopen", function( event, ui ) {
var window_height = $(window).height();
var thestyle = 'min-height:' + window_height + 'px';
$("div:jqmData(role='page')").attr('style', thestyle);
});

I've had these issues before, and I know this probably isn't the best way to fix it but it has worked for me in the past. Set the style in the div property.
<div data-role="page" style="min-height: 0;">

You have to override the resize function and prevent the propagation of the event:
$(window).on("resize", function (event) {
// Make your stuff with the page height:
// $.mobile.activePage.css("min-height", "999px");
event.stopImmediatePropagation();
});

Related

Bing Autosuggest Dropdown Responsive CSS

I am testing out the documentation here. The only difference is my searchBox is responsive and has 100% width.
<div id='searchBoxContainer'>
<input type='text' id='searchBox' style="width:100%"/>
</div>
On mobile the searchBoxContainer does not honor the width of the searchBox. The red overhang below expands my mobile app and doesn't feel good.
I have determined I can fix this by setting the as_container max-width equal to the width of the searchBox as it changes.
#as_container {
max-width: width of search box;
}
Is there a way to set the #as_container max-width dynamically as the searchBox width changes? I've fixed this with $(window).resize and a little javascript but I feel like there is CSS to handle this?
Here is what I came up with. It's really simple I would just prefer a CSS solution. In my case the searchBox is responsive to it's container, style="width:100%". On resize I match bings drop down container's max-width to the searchBox. The container's width can be set with #as_container.
// Our responsive fix for the autosuggest is to limit it's max width to the dropdown container. (Assuming our searchBox is responsive, we'll match widths)
function FixAutoSuggest() {
try {
var css = document.getElementById("autoSuggestFix");
// Create a CSS element for our fix if it hasn't been created already.
if (!css) {
css = document.createElement("style");
css.setAttribute("id", "autoSuggestFix");
css.type = "text/css";
document.body.appendChild(css);
}
// Set the appropriate width for our auto suggest container.
var searchBox = document.getElementById('searchBox')
if (searchBox != null) {
var bb = searchBox.getBoundingClientRect(), columnWidth = bb.right - bb.left;
// We set column width minimum to 150.
columnWidth = ((columnWidth > 150) ? columnWidth : 150);
css.innerHTML = "#as_container { max-width: " + columnWidth + "px }";
}
}
catch (err) {
alert('FixAutoSuggest' + err);
}
}
$(window).resize(function () {
FixAutoSuggest();
});
In my case the search box is not shown initially and I call FixAutoSuggest() when showing it. If you show it on load you could always fix then as well.
$(document).ready(function () {
FixAutoSuggest();
});
You'll notice in FixAutoSuggest() I put a minimum width of 150px on the bing drop down. That's just personal preference and you can remove that line if you want it to shrink to nothing. Hope this helps someone!

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>

Disabling Page Scroll when Cursor is Over Div (Chatango)

I'm adding a Chatango HTML5 chat box to my website, but when users scroll up or down in the chat box, it also scrolls up or down the rest of the page. I've been experimenting with different codes I've found on this site, but so far nothing has worked.
I thought I found a solution here: How to disable scrolling in outer elements? and applied it to my chatroom. It works exactly how I want it to on this codepen editor: http://codepen.io/EagleJow/pen/QbOBJV
But using the same code in JSFiddle: https://jsfiddle.net/4bm6ou90/1/ (or on my actual website) does not prevent the rest of the page from scrolling. I've tested it in both Firefox and Chrome with the same results.
Here's the javascript:
var panel = $(".panel");
var doc = $(document);
var currentScroll;
function resetScroll(){
doc.scrollTop(currentScroll);
}
function stopDocScroll(){
currentScroll = doc.scrollTop();
doc.on('scroll', resetScroll);
}
function releaseDocScroll(){
doc.off('scroll', resetScroll);
}
panel.on('mouseenter', function(){
stopDocScroll();
})
panel.on('mouseleave', function(){
releaseDocScroll();
})
Any ideas?
It didn't work on JSFiddle because I didn't have jQuery set on the side menu and it didn't work on my website because the '$' symbol in the javascript conflicted with that same symbol in the jQuery (or something like that).
Here's the JSFiddle with better code and set to load jQuery: https://jsfiddle.net/4bm6ou90/7/
The Javascript:
$.noConflict();
jQuery( document ).ready(function( $ ) {
$(".panel").on("mouseenter", function(){
$(document).on("scroll", function(){
$(this).scrollTop(0);
});
});
$(".panel").on("mouseleave", function(){
$(document).off("scroll");
});
});
Also gotta have that jQuery CDN in the html head section.

No CAPTCHA reCAPTCHA Resizing

Hi I just added Google's No CAPTCHA reCAPTCHA to my website, and I am running into a small little issue. It does NOT fit on my mobile website, and that is a HUGE issue. I have tried everything such as:
HTML
<div id="captchadisplay">
<div class="g-recaptcha" data-sitekey="???"></div>
</div>
CSS
#captchadisplay {
width: 50% !important;
}
and
CSS
.g-recaptcha {
width: 50%;
}
Yet I can not seem to shrink it down for my mobile website. Any ideas? :)
By using the CSS transform property you can achieve changing the width by changing the entire scale of the reCAPTCHA.
By adding in just two inline styles, you can make the reCAPTCHA fit nicely on your mobile device:
<div class="g-recaptcha"
data-theme="light"
data-sitekey="XXXXXXXXXXXXX"
style="transform:scale(0.77);-webkit-transform:scale(0.77);transform-origin:0 0;-webkit-transform-origin:0 0;">
</div>
More details can be found on my site: https://www.geekgoddess.com/how-to-resize-the-google-nocaptcha-recaptcha/
I successfully implemented Geek Goddess' solution. The main issue with it is that it may not work on all browsers. Now, however, there is a simple solution provided by Google.
With reCAPTCHA version 2.0, there are new rules for the display of the widget and Google added tag attributes that change the way it is rendered.
The tag data-size can take the values of "normal", which is the default, and "compact", which fits in mobile device screens. This is what the compact widget looks like.
It is not the best looking widget, but it fits with less work than the other solutions.
For more attributes, check Google's reCAPTCHA v2.0 documentation
I have been using some JQuery, since putting transform(0.77) in the style attribute wasn't a truly responsive solution.
I add this media query in my CSS, with the max-width being the threshold where the ReCaptcha box is considered too large once passed:
#media(max-width: 390px) {
.g-recaptcha {
margin: 1px;
}
}
I then add this JQuery:
$(window).resize(function() {
var recaptcha = $(".g-recaptcha");
if(recaptcha.css('margin') == '1px') {
var newScaleFactor = recaptcha.parent().innerWidth() / 304;
recaptcha.css('transform', 'scale(' + newScaleFactor + ')');
recaptcha.css('transform-origin', '0 0');
}
else {
recaptcha.css('transform', 'scale(1)');
recaptcha.css('transform-origin', '0 0');
}
});
The 304 I use is the default width of the ReCaptcha box if unstyled.
Now the ReCaptcha will properly scale down no matter how small its parent container becomes, and it will behave as if it has a maximum width at its original width.
Note that the media query is simply a mechanism to detect a screen size change.
According to the documentation from Google shows a data-size attribute which can be set and this worked for me.
<div class="g-recaptcha" data-sitekey="XXXXXXXX" data-size="compact"></div>
But, the answer from #GeekGoddess provides a little more flexibility in sizing.
For me the compact mode implementation of Google re-captcha 2.0 is just lame. It looks ugly.
Just expanding from "Geek Goddess" solution.
You can do the following:
<div class="g-recaptcha" data-sitekey="..." style="-moz-transform:scale(0.77); -ms-transform:scale(0.77); -o-transform:scale(0.77); -moz-transform-origin:0; -ms-transform-origin:0; -o-transform-origin:0; -webkit-transform:scale(0.77); transform:scale(0.77); -webkit-transform-origin:0 0; transform-origin:0; filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.77,M12=0,M21=0,M22=0.77,SizingMethod='auto expand');"></div>
That will resize on almost all browsers IE, Chrome, FF, Opera (DXImageTransform is for IE <= 8).
Furthermore we can make it responsive by combining this transform scale with CSS max-width.
It's not the perfect way, but until we get the proper responsive fix from Google.
If you don't like the CSS solution, you may try the JS.
The idea is to dynamically switch between compact and normal mode of the recaptcha plugin.
I will provide an example with jQuery onboard, but it shouldn't be much to port it to pure JS.
I assume you have following HTML code on the site.
<div>
<div class="g-recaptcha" data-sitekey="[your-key-here]"></div>
</div>
Firstly you need to load gRecaptcha 2 explicitly and provide onload callback:
<script type='text/javascript' src='https://www.google.com/recaptcha/api.js?hl=en&onload=recaptchaCallback&render=explicit'>
Next, create your callback function which will also be your javascript media query.
function recaptchaCallback()
{
var mq = window.matchMedia("(max-width: 400px)");
mq.addListener(recaptchaRenderer);
recaptchaRenderer(mq);
}
The last thing is to render the recaptcha widget.
function recaptchaRenderer(mq)
{
var recaptcha = $('.g-recaptcha').eq(0);
var data = recaptcha.data();
var parent = recaptcha.parent();
recaptcha.empty().remove();
var recaptchaClone = recaptcha.clone();
parent.append(recaptchaClone);
recaptchaClone.data(data);
var options = {
'sitekey': data['sitekey'],
'size': 'compact'
};
if(!mq.matches)
{
options['size'] = 'normal';
}
grecaptcha.render(recaptchaClone.get(0), options);
}
You may wonder why I empty the div and clone all the g-recaptcha content. It's because gRecaptcha 2 wouldn't let you render second time to the same element. There could be a better way, but it's all I found for now.
Hope this works for you.
<div class="g-recaptcha" data-theme="light" data-sitekey="XXXXXXXXXXXXX" style="transform:scale(0.77);transform-origin:0 0"></div>
Just add style="transform:scale(0.77);transform-origin:0 0"
For who might be interested, I changed a little AjaxLeung solution and came up with this:
function resizeReCaptcha() {
if ($(".g-recaptcha").length) {
var recaptcha = $(".g-recaptcha");
recaptcha.parent().addClass('col-xs-12 padding0');
var innerWidth = recaptcha.parent().innerWidth();
if (innerWidth < 304) {
var newScaleFactor = innerWidth / 304;
recaptcha.css('transform', 'scale(' + newScaleFactor + ')');
recaptcha.css('-webkit-transform', 'scale(' + newScaleFactor + ')');
recaptcha.css('transform-origin', '0 0');
recaptcha.css('-webkit-transform-origin', '0 0');
} else {
recaptcha.css('transform', 'scale(1)');
recaptcha.css('-webkit-transform', 'scale(1)');
recaptcha.css('transform-origin', '0 0');
recaptcha.css('-webkit-transform-origin', '0 0');
}
}
}
$(window).resize(function() {
resizeReCaptcha();
});
$(document).ready(function () {
resizeReCaptcha();
});
Here's my spin on the resize:
<script>
function resizeReCaptcha() {
var width = $( ".g-recaptcha" ).parent().width();
if (width < 302) {
var scale = width / 302;
} else {
var scale = 1;
}
$( ".g-recaptcha" ).css('transform', 'scale(' + scale + ')');
$( ".g-recaptcha" ).css('-webkit-transform', 'scale(' + scale + ')');
$( ".g-recaptcha" ).css('transform-origin', '0 0');
$( ".g-recaptcha" ).css('-webkit-transform-origin', '0 0');
};
$( document ).ready(function() {
$( window ).on('resize', function() {
resizeReCaptcha();
});
resizeReCaptcha();
});
</script>
Unfortunately, NoCaptcha uses an iframe so at most you can control the height/width and use overflow:hidden; to cut off the excess. I would not recommend cutting off more than a few pixels of the Captcha for best usability.
Example:
.g-recaptcha {
max-width: 300px;
overflow: hidden;
}
On my site the re-captcha was getting cut off and looked bad.
After some experimentation I was able to fix the cutoff issue with this style update:
<style>
.g-recaptcha>div>div>iframe {
width: 380px;
height: 98px;
}
</style>
Hope you find this useful
#media only screen and (max-width : 480px) {
.smallcaptcha{
transform:scale(0.75);
transform-origin:50% 50%;
}
}
<div class="g-recaptcha" data-theme="light" data-sitekey="your site key" style="transform:scale(0.77);-webkit-transform:scale(0.77);transform-origin:0 0;-webkit-transform-origin:0 0;"></div>
This working for me, you try it..
<div class="g-recaptcha" data-theme="dark"></div>

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

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;
}