So I have this:
clicking here
<a name="link">goes here</a>
Simple, but the problem is that my site has a fixed position header that stays at the top of the page, so when a user clicks on the link, the place I want them to go to is hidden by the header. So I guess where I really want them to end up a certain amount of pixels above what I actually want them to see. I've tried putting the destination link above where I want them to end up, but it's a block of text so it changes with different screen sizes and therefore isn't consistent.
I'm wondering if there is any way to solve this problem, perhaps something with css.
Thanks in advance.
I realise this is over a year old, but for the benefit of anyone else who comes across it:
A slightly simpler solution is to put padding at the top of the section you are targeting with the link.
HTML:
<section id="section_name">
...Your stuff here...
</section>
CSS:
#section_name {
padding-top: 40px;
}
You could use a jQuery method so that when a link with a # is clicked, it finds the position of the element it's meant to go to and then moves to a position X number of pixels above the target.
Something like this:
$(function(){
var positionOffset = 50;
$('a[href=*"#"]').click(function(){
var targetHash = this.hash;
if(targetHash.length > 0 && targetHash == window.location.hash){
var elementPosition;
if($(targetHash).length){
elementPosition = $(targetHash).offset();
} else {
var targetAnchor = targetHash.replace("#", "");
elementPosition = $('a[name="' + targetAnchor + '"]').position();
}
$(window).scrollTop(elementPosition.top - positionOffset);
return false;
} else {
return true;
}
});
});
Related
I have this button that will hide when no more content to load in review page. The button is working great except that it will still show up even if there are no more data to display. I want it to not show up if there is nothing left to load. Does anyone have any suggestions? Thank you.
Here is my code
$(document).unbind('click').on('click', ".recentreviews5 .showmore", function () {
$('#last').val(parseInt($('#last').val()) + 10)
$('.hide').each(function () {
var itmidx = $(this).index();
if (parseInt(itmidx) < parseInt($('#last').val())) {
var g = $(this).attr('id')
$(this).removeClass('recent').removeClass('hide')
$(this).addClass('recent').addClass('show')
}
});
if ((parseInt($('#last').val()) >= parseInt($('#total').val())) || (parseInt($('#last').val()) < 10)) {
$(".showmore").css('cssText', 'display:none!important')
}
});
You can use this code to manually set the style. The .css call generally speaking doesn't support !important.
$(".showmore").attr('style', 'display: none !important')
$(".showmore").attr('hidden', 'hidden')
This code toggle visibility with display:none / display:block
$(".showmore").toggle();
Here's the layout I'm trying to achieve:
My content currently is a series of basic, block HTML elements (h[1-5], p, ul, etc.) contained in a div, and if possible I'd like to keep them that way. All of the images are inside their own p in order to responsively resize
I've been able to add a div style="float:right" to the top of the content which creates the sidebar and wraps "normal" text content around it - specifically the first paragraph in my diagram above. However, the img, which is set to 100% does not wrap, it flows below the sidebar.
So really, I want images to have one of two widths - either 100%-width(sidebar) if the top of the image "should be" above the bottom of the sidebar, or 100% if the top of the image is below the bottom of the sidebar.
I can of course manually set the width on an image when debugging a page, to a value less than 100%-width(sidebar) and it jumps right up into place, so clearly the browser knows what that size is to not "push" the image down below the sidebar...
Here's the actual page where I'd like to get this to work; note that the first image is below the sidebar:
https://adventuretaco.com/?p=3655&draftsforfriends=kIq7mVDhNtCSklITGCJs2HAcE9xuPX8d
additionally, here is the CSS and HTML that I currently have for the post content:
CSS
p {
margin: 0 0 1.25em 0;
}
ol, ul {
margin: 0 1.5em 1.25em 1.5em;
}
.full-width-container {
width: 100%;
}
.full-width-container img {
display: block;
margin-left: auto;
margin-right: auto;
overflow: hidden;
transition: 0.5s;
}
.full-width-container img.flickrPhoto {
display: block;
width: 100%;
margin-left: auto;
margin-right: auto;
overflow: hidden;
transition: 0.5s;
}
HTML
<div class="post-content">
<p>As you may recall, we'd just cancelled our flight home due to the unknowns of Covid-19, but were still in exploration mode as we entered the Valley of Fire State Park in southeastern Nevada.</p>
<p id="photoContainer132" class="full-width-container"><img id="photo132" class="flickrPhoto" src="https://live.staticflickr.com/65535/49714173358_d19b1c2e70_n.jpg" /></p>
<p>Our trip to the Valley of Fire was somewhat opportunistic to say the least. A year before this trip ever even crossed my mind, I'd seen a photo on Flickr that had caught my eye. Sharp as ever, I completely forgot to save the photo or a link to the photo <img src="https://www.tacomaworld.com/styles/default/my/smilies/annoyed_gaah.gif" />, but - luckily for me - the photo had been geotagged <em>and</em> I'd saved a point of interest in my Google Earth map of Nevada. I'd noticed that point as I'd planned this trip, and mapped out the route, excited to see what nature had in store. So yeah, apparently, I'm not <em>always</em> as dumb as I look. <img src="https://www.tacomaworld.com/styles/default/my/smilies/original/wink.png" /> In researching Valley of Fire, I also discovered a second hike -rumored to have petroglyphs - and since it was on our way to the main attraction, we decided to stop off there first.</p>
<p id="photoContainer133" class="full-width-container"><img id="photo133" class="flickrPhoto" src="https://live.staticflickr.com/65535/49715029457_a61cffc61b_n.jpg" /></p>
</div>
I think you first need to downsize a little your images, due to their size, it becomes a little difficult to manipulate them within the scope of what you would like to do. You can alter them inside the tag, or from the css file. Then after, you can use inside of that code a "float: left;" in the .full-width-container img, give it a margin that should put them side to side.
OK, so after a bunch more research, trial and error, I've come to the conclusion that the answer to this question is that it cannot be solved with CSS / layout alone.
In the end, incorporated Javascript to solve the problem. It's not perfect - if images have been downsized to flow around the sidebar, then when the browser window gets larger, they don't get larger as ideally as they could.
Here's where I ended up; working sample at (scroll down here to see the sidebar)
https://adventuretaco.com/hidden-valleys-secret-tinaja-mojave-east-5/#photoContainer190
// start shortly after page is rendered
setTimeout(resizeImagesForFacebookEmbed, 500);
function resizeImagesForFacebookEmbed() {
var tryAgain = true;
// find each of the elements that make up the post, and iterate through each of them
var content = jQuery('div.post-content').children().each(function () {
if (this.tagName.toLowerCase() == 'p') {
var firstChild = this.firstChild;
var firstElementChild = this.firstElementChild;
if (firstChild != null && firstChild == this.firstElementChild && firstElementChild.tagName.toLowerCase() == 'img') {
var pRect = this.getBoundingClientRect();
var imgRect = firstChild.getBoundingClientRect();
var difference = imgRect.top - pRect.top;
// if the image contained in the p is not at the top of the p, then make it smaller
// so it will fit next to the embed, which is 350px wide
if (difference > 25 || imgRect.width < (pRect.width - 400)) {
var sidebarLeft = document.getElementById("fbSidebar").getBoundingClientRect().left;
var imgLeft = firstChild.getBoundingClientRect().left;
var imgWidth = (sidebarLeft - imgLeft) * .95;
firstChild.style.width = imgWidth + "px";
tryAgain = false;
setTimeout(resizeImagesForFacebookEmbed, 1000);
} else {
// do nothing
}
}
}
});
if (tryAgain)
setTimeout(resizeImagesForFacebookEmbed, 1000);
}
var waitForFinalEvent = (function () {
var timers = {};
return function (callback, ms, uniqueId) {
if (!uniqueId) {
uniqueId = "Don't call this twice without a uniqueId";
}
if (timers[uniqueId]) {
clearTimeout(timers[uniqueId]);
}
timers[uniqueId] = setTimeout(callback, ms);
};
})();
// handle window resize event to re-layout images
jQuery(function () {
jQuery(window).resize(function () {
waitForFinalEvent(function () {
resizeImagesForFacebookEmbed();
}, 500, "atFbEmbedId"); // replace with a uniqueId for each use
});
});
I have an 'overview' html page with lots of product images - each image links to a page that may have 3 or 4 products, eg, src="gadgets-1.html"
On desktop, on the destination page the user can see most products or can easily scroll down if needed.
But on narrow screen where the css MQs convert all columns to 100% width, the last items are not necessarily in view and the user must intuit that it's necessary to swipe down the page, so I want the linking image to link directly to the relevant item on the destination page.
I've established anchor links which work well, eg, src="gadgets-1.html#red-thing" but I don't want the '#red-thing' to be active on wider screens.
To resume, I want the link to be gadgets-1.html on wider screen and
gadgets-1.html#red-thing on narrow screen.
I don't see how this can (or should) be done with css. Should js or php be used? If so, how?
There are a couple of solutions I can think off of the top of my head. I don't usually like using javascript to modify the DOM based on screenwidth but it is an acceptable solution if you are so inclined.
OR you can do something simple like this:
<div class="links">
<a class="mobileLink" href="gadgets-1.html#red-thing">gadgets-1</a>
<a class="desktopLink" href="gadgets-1.html">gadgets-1</a>
</div>
with some css to hide the right link based on screen width
.mobileLink{
display: none;
}
#media screen and (max-width: 992px) {
.mobileLink{
display: inline-block;
}
.desktopLink{
display: none;
}
}
A flexible solution would be to use Javascript with a specific data- attribute for storing the different anchor names.
HTML:
<a class="targetLink" href="/link1" data-anchor="anchor-name1">Target link</a>
<a class="targetLink" href="/link2" data-anchor="anchor-name2">Target link</a>
To execute the code cross-browser on DOM ready and window resize, jQuery would be useful.
Check CodePen here
$(document).ready(function() {
var $target = $(".targetLink");
var $window = $(window);
var breakpoint = 640;
var linkSmall = false;
function checkWidth() {
if ($window.width() <= breakpoint) {
// appends anchors to links
if(!linkSmall){
$target.each(function(index) {
var href2 = $(this).attr("href") + "#" + $(this).attr("data-anchor");
$(this).attr("href", href2 );
});
linkSmall = true;
}
}else{
// removes anchors to links
if(linkSmall){
$target.each(function(index) {
var href1 = $(this).attr("href");
var a = href1.indexOf('#');
var href2 = href1.substring(0, a != -1 ? a : href1.length);
$(this).attr("href", href2 );
});
linkSmall = false;
}
}
}
checkWidth(); // on document ready
$(window).resize(checkWidth); // on window resize
});
As you don't want to repeat anchor elements(as per the other threads), you won't be able to do it with css so you'll have to use js.
if(window.innerwidth < 911){
document.getElementsByClassName("class")[0].setAttribute("href", "url_for_small_screen_devices);
}else{
document.getElementsByClassName("class")[0].setAttribute("href", "url_for_normal_desktop_and_bigger_devices");
}
you can use a loop to repeat the same process for all anchors with using proper selectors.
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;
}
I'll try to explain:
I have numerous div classes, but for the sake of simplicity, let's say I only have 3.
Someone is viewing DIV 1, and I want to give them the option of only printing DIV 1, omitting 2 and 3.
However, on the same page, I would like to give them the option to ONLY PRINT DIV 2. Or only print DIV 3.
I think I get how you can omit certain things from getting printed. But how can you select a section here or there on the same page to be printed with a print link.
Thanks,
Tracy
You can use jQuery to show/hide divs. Read the jQuery tutorial:
http://docs.jquery.com/Tutorials
The code will look this way:
<script>
function showDiv(n) {
$('.divs').hide();
$('#div_'+n).show();
}
$(document).ready(function() { showDiv(1); });
</script>
<a href='javascript:showDiv(n)'>show div n</a>
<div class='divs' id='div_n'>I'm div n</div>
There are many related posts on printing div content, this particular question was still open though it was asked in '10.. Following JavaScript function can be used for printing content of a selected Div tag. Hope this helps. Declaimer: I used some of the existing answers, fixed/enhanced code/error(s) to work with (and tested on) IE-8.
function printDiv(divName) {
var divToPrint = document.getElementById(divName);
var newWin = window.open('', 'PrintWindow', 'width=400, height=400, top=100, left=100', '');
newWin.document.open();
newWin.document.write('<html><body onload="window.print()">' + divToPrint.innerHTML + '</body></html>');
newWin.document.close();
setTimeout(function () { newWin.close(); }, 10);
}
Call printDiv from anywhere in page or from within selected Div. Here is test link:
Print Customer Data
Print Order Data
Assign respective IDs to Div that is to be printed:
<div id="divCustomerData">Div Contents goes here... </div>
The only catch right now is it loses css styles. I'll update response when i get a chance to fix it. Thanks.
https://github.com/jasonday/jquery.printThis
I would give each div an id, and then using the above plugin (i wrote) specify according to div id.