jQuery - stop url anchors from changing page position - javascript

I have a document with a bunch of sections that have information that I need to gather based on the URL anchor.
Example of what I'm trying to do:
URL
http://mywebsite.com/page.php#section-2
html
<div id='information'>Data should be here!</div>
<div id='section-1'>This is data from section 1!</div>
<div id='section-2'>This is data from section 2!</div>
<div id='section-3'>This is data from section 3!</div>
<div id='section-4'>This is data from section 4!</div>
CSS
div{
height: 500px;
}
jQuery
var hash = window.location.hash;
if(!hash == ""){
var data = $(hash).text();
$("#information").text(data);
}
But when I load the URL, The jQuery works fine, But the page jumps down to #section-2.
How do I stop this from happening?
Thanks in advance.

You condition is incorrect. It should be != instead.
if(hash != ""){
var data = $(hash).text();
$("#information").text(data);
}
And to prevent from jumping you can try using scrollTop().
$(document).ready(function(){
var hash = window.location.hash;
if(hash){
$('body').scrollTop(0);
}
});
div{
height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id='information'>Data should be here!</div>
<div id='section-1'>This is data from section 1!</div>
<div id='section-2'>This is data from section 2!</div>
<div id='section-3'>This is data from section 3!</div>
<div id='section-4'>This is data from section 4!</div>

the browser will jump if there is a visible div with id = hash in the page. One way to prevent this is to set your divs display = none in the css so they are not visible during page load and then change them to visible immediately after
$(function() {
$('div').show();
});
Or perhaps you might only want to show one section at a time..
$(function() {
$('#section-2').show();
});
another way might be to leave the divs visible but immediately scroll back to top of page
$(function() {
self.scrollTo(0, 0);
});

I managed to find a way to fix it!
For some reason, The timing was messing it up and causing the $('body').scrollTop(0); not to work.
I was able to fix it by adding a 10 ms delay before scrolling to the top of the page.
$(document).ready(function(){
if(hash){
setTimeout( function(){
$('body').scrollTop(0);
}, 10 );
}
});

I managed to find a way to fix it!
For some reason, The timing was messing it up and causing the $('body').scrollTop(0); not to work.
I was able to fix it by adding a 10 ms delay before scrolling to the top of the page.
$(document).ready(function(){
if(hash){
setTimeout( function(){
$('body').scrollTop(0);
}, 10 );
}
});

Related

Smooth scrolling with timer in HTML

Synopsis:
The main idea behind this is to auto smooth scroll to the testimonials section of my html after a certain amount of time.
Achieved so far:
I'm able to scroll to the testimonials section of the page after X seconds without any problems using a simple script in my main index.html page. The script code is given below.
Auto scroll in the page after 5secs
<script>
setTimeout(function(){
window.location.hash = '#testimonials';
},5000);
</script>
Problem facing:
I've smooth scrolling in the entire page, but for the timer scrolling in my page, I'm unable to use smooth scroll. The uncertain transition is looking awkward, hence, I want to make it smooth scroll.
Also, I want this to happen only for the first time on page loading, i.e., if any operation is done in the page, this will not happen if visited index.html again.
TIA guys!
function goTo(selector, timeout, cb) {
var $el = $(selector);
if (!$el[0]) return;
var $par = $el.parent();
if ($par.is("body")) $par = $("html, body");
setTimeout(() => {
$par.stop().animate({scrollTop: $el.offset().top}, 1000, cb && cb.call($el[0]));
}, timeout || 0);
}
// USE LIKE:
goTo("#testimonials", 3000, function() {
// You can use `this` to reference #testimonials! yey
$(this).append("<br>Going to #contact in 3sec!");
goTo("#contact", 3000);
});
// Alternatively, without using callbacks you can do
// goTo("#testimonials", 3000);
// goTo("#contact", 6000);
// Reuse function for elements click!
$("[href^='#']").on("click", function(e) {
e.preventDefault();
goTo($(this).attr("href"));
});
/*QuickReset*/
*{margin:0;box-sizing:border-box;} html,body{height:100%;font:14px/1.4 sans-serif;}
article {
height: 150vh;
}
<article style="background:#0bf;" id="top">WELCOME (wait 3 sec)</article>
<article style="background:#f0b;" id="about">ABOUT</article>
<article style="background:#b0f;" id="work">OUR WORK</article>
<article style="background:#0fb;" id="testimonials">TESTIMONIALS</article>
<article style="background:#fb0;" id="contact">
CONTACT TO TOP
</article>
<script src="//code.jquery.com/jquery-3.1.0.js"></script>

How to capture a new group of selector after loading a div with .load() of Jquery

Currently, my website http://benoitmignault.ca/english/english.html works well on Chrome or Firefox, but on IE the fetch functions doesn't work...
I started to understand Jquery because the .load () function works well on IE because the fetch function doesn't work...
I managed to display each of my links in the "header" section in the div_center section.
When I click on the pictures section, my 5 links are displayed.
When I come to click on one of the 5 pictures it does not display the content in the section «div_photo», but rather the content of the page html is displayed as a new page ...
const listeSections = document.querySelectorAll('.header div a');
function affichageSection(){
$(listeSections).each(function(){
$(this).on('click', function(evt){
evt.preventDefault();
if (evt.target.href === "http://localhost:8080/english/english.html"){
window.location.assign("/english/english.html");
} else if (evt.target.href === "http://localhost:8080/index.html"){
window.location.assign("/index.html");
} else if (evt.target.href === "http://localhost:8080/pageAccueuil/partie_photos_EN.html"){
$(div_Center).load(evt.target.href);
affichageSectionPhoto();
} else {
$(div_Center).load(evt.target.href);
$(div_Photo).append("");
}
});
});
}
This is my function that does not work well and I can not understand where my mistake is, it's been days that I'm going around in circles ...
function affichageSectionPhoto(){
var allListElements = $(".unePassionPhoto a");
$(div_Center).find(allListElements).each(function(){
$(this).on('click', function(e){
e.preventDefault();
$(div_Photo).load(e.target.href);
}
});
});
}
Here is the portion of my code from my index.html page:
<div class="middle">
<div class="header">
<div>Accueil
</div>
<div>Projets
</div>
<div>Photos
</div>
<div>À propos
</div>
<div>English</div>
</div>
<div class="center"></div>
<div class="photo"></div>
</div>
I tried to find the information on https://learn.jquery.com/ but without success or to use the "console.log ()" function
thank you in advance
This is my console.log(div_Center)
My console log

Open Expanding List from Href

I'm trying to modify this pen I found on CodePen. I'd like to be able to open a specific list on the page from another page. Clicking the link should open the corresponding section on the next page on page load.
I'm a bit of a newbie when it comes to jQuery, so I appreciate any help I can get. I've tried searching around and have an idea of what I need to target, but I haven't been able to make it happen. Here is my code:
HTML:
<!--Link on Previous Page-->
Click Here
<!--Target List-->
<div class="integration-list">
<ul>
<li class="integration">
<a class="expand" id="list">
<div class="expand_intro"><h3 class="teal_bold">Click Here</h3></div>
<div class="right-arrow">▼</div>
</a>
<div class="detail">
<div><p>Lorem Ipsum Dolor...</p></div>
</div>
</li>
</ul>
</div>
JS:
$(function() {
$(".expand").on( "click", function() {
$(this).next().slideToggle(100);
$expand = $(this).find(">:nth-child(2)");
if($expand.text() == "▼") {
$expand.text("▲");
} else {
$expand.text("▼");
}
var hash = window.location.hash;
var thash = hash.substring(hash.lastIndexOf('#'), hash.length);
$('.expand').find('a[href*='+ thash + ']').trigger('click');
});
});
Few things that I did to get it to work:
The trigger event is probably firing before the handler is actually attached. You can use setTimeout as a way around this.
Also, even with setTimeout around $('.expand').find('a[href*='+ thash + ']').trigger('click'); it didn't work for me. I changed that to simply $(thash).click();.
The complete code of the "expand.js" file:
$(function() {
var hash = window.location.hash;
var thash = hash.substring(hash.lastIndexOf('#'), hash.length);
setTimeout(function() {
$(thash).click();
}, 10);
$(".expand").on( "click", function() {
$(this).next().slideToggle(100);
$expand = $(this).find(">:nth-child(2)");
if($expand.text() == "â–¼") { //If you copy/paste, make sure to fix these arrows
$expand.text("â–²");
} else {
$expand.text("â–¼");
}
});
});
Apparently the arrows don't display properly here, so watch that if you copy/paste this.

jQuery loads external HTML file but does not stay still after page refresh

I am trying to do something different without knowing if it is a good idea or not
I have a navigation menu as the following:
...
<li>Home</li>
<li>FAQ</li>
<li>Contact</li>
...
I do not want to use a server-side scripting because it takes more time to make db connection and define some configuration, and not want to multiply the pages for each one. So I made a master page index.php
in body section
there are two elements:
an h3 element to display the page title and a div to display the content which is called from another html source.
...
<div class="container">
<h3 id="pageTitle"></h3>
<div id="pageContent"></div>
</div>
...
I am using jQuery's click event to load the page into the div
$(function() {
$("a[href^='#m']").click(
function() {
$("#pageTitle").text($(this).text());
$("#pageContent").load($(this).attr("href").substring(1) + ".html"); //removing # char.
});
});
It works fine. But when I press F5 it returns the initial state as normal. How can I load the current page by referencing the address bar (I can see eg. sitename/#mfaq) when page is refreshed.
I think, first I need to detect if page is refreshing and load the corresponding html file in according to the #m**** on the addressbar.
$(function() {
$("a[href^='#m']").click( function(evt) {
// ------ This should work
// renamed parameter elem to evt like corrected in comment
evt.preventDefault();
$("#pageTitle").text($(this).text());
$("#pageContent").load($(this).attr("href").substring(1) + ".html");
});
});
Add to your DOM ready function:
if (window.location.hash != "") {
$("#pageTitle").text($("a[href='"+window.location.hash+"']").text());
$("#pageContent").load(window.location.hash.slice(1) + ".html");
}
I have made this. It works well. But I am not sure about performance issues:
$(function() {
var address = $(location).attr('href');
var hash = address.lastIndexOf("#");
var page = address.substring(hash+1);
if (hash < 1)
{
$("#pageContent").load("mhome.html");
$("#pageTitle").html("Default Page Title");
}
else
{
$("#pageContent").load(page + ".html");
$("#pageTitle").html($("a[href='" + address.substring(hash) + "']").text());
}
$("a[href^='#m']").click(
function() {
$("#pageTitle").text($(this).text());
$("#pageContent").load($(this).attr("href").substring(1) + ".html");
});
});

Jquery menu slide up from from bottom of screen on hover

I want to only show the menu phrases "music, newsletter, contact" fixed at the bottom of the screen. On hover I want them to slide up and reveal hidden content. here's exactly what I mean:
http://sorendahljeppesen.dk/
See the bottom of the screen. Anyone know how this would be accomplished? Thank you.
P.S. also, would anyone know what type of MP3 player that is?
Put your hidden content into a div such as;
<div class="hiddenContent">...</div>
Then give your links at the bottom of the page a class such as;
Music
Then tell the Jquery to show the hidden content when you hover over the link;
$('.bottomLink').hover(
function () {
// Show hidden content IF it is not already showing
if($('.hiddenContent').css('display') == 'none') {
$('.hiddenContent').slideUp('slow');
}
},
function () {
// Do nothing when mouse leaves the link
$.noop(); // Do Nothing
}
);
// Close menu when mouse leaves Hidden Content
$('.hiddenContent').mouseleave(function () {
$('.hiddenContent').slideDown('slow');
});
Try this code:
ASPX section,
<div id="categories-menu" class="hover-menu">
<h2>Categories</h2>
<ul class="actions no-style" style="display: none">
<li>//Place your content here that should show up on mouse over</li>
</ul>
</div>
JQuery section,
<script type="text/javascript">
$(document).ready(function() {
function show() {
var menu = $(this);
menu.children(".actions").slideUp();
}
function hide() {
var menu = $(this);
menu.children(".actions").slideDown();
}
$(".hover-menu").hoverIntent({
sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)
interval: 50, // number = milliseconds for onMouseOver polling interval
over: show, // function = onMouseOver callback (required)
timeout: 300, // number = milliseconds delay before onMouseOut
out: hide // function = onMouseOut callback (required)
});
});
</script>
Hope this helps...
I have found this great article with live demo and source code to download, the article show how to make a slide out menu from bottom.

Categories