in a current project i have different articles containing different headings (<h3>). Because the articles are composed in a CMS we cannot set the id of the <h3> element from the beginning on. Thats why I'm setting them on page load:
$(document).ready(function(){
let articleContent = $(".article-body")
let headings = articleContent.find("h3")
headings.each(function() {
$(this).attr("id", $(this).first().text().replace(/\s/g, "-"))
}
}
The problem is, when I try top open the URL with the given id of the heading as its hash to navigate the user to the right heading (eg. https://test.com/article-122321#heading2), this is not working. I guess this is the case because on page load the headings do not have any ids set and the browser doesn't know where to navigate to.
Can you help out with a solution for that? Do I have to set the ids at another point of time or do I need some custom Javascript code to tell the browser to navigate to the heading?
Thanks!
Have a try of this
$(document).ready(function() {
$(".article-body h3").each(function() {
$(this).attr("id", $(this).first().text().replace(/\s/g, "-"))
})
const hash = location.hash;
const $element = hash ? $(hash) || null; // assuming a valid selector in the hash
if ($element) $element[0].scrollIntoView({ // use the DOM method
behavior: "smooth", // or "auto" or "instant"
block: "start" // or "end"
});
});
Related
I have one page website which changes URL #id or anchor text on scrolling and on navigation click. I have an image positioned fixed at the center of the site. The site is divided in different sections and the image shows in all the sections. I do not want to show the image on the first section as it is unrelated to the content of the 1st section but will be showed in all next sections. How can I make it work?
What I have tried till now but not working:
$(document).ready(function(){
$(".phone").hide();
var idSample = window.location.href.split("#");
var id = "#"+idSample[1];
if($(id) == "second"){
$(".phone").show();
}else{
$(".phone").hide();
}
});
Rest in Fiddle: https://jsfiddle.net/shubhamjha1000/vh7bu32q/
I don't want that phone to be seen on 1st section but on rest of the sections. Please help me guys!
You can use the answer written in this question to listen to changes in the window see what url you are on and show or hide the phone accordingly....
Example:
$(function(){
// Bind the event.
$(window).hashchange(hashchanged);
// Trigger the event (useful on page load).
hashchanged();
});
function hashchanged(){
var hash = location.hash.replace( /^#/, '' );
//your code
if(hash == "#first") {
// Hide element
} else {
// Show element
}
}
But still even though what you are planning to do will work with that solution I think it would still look bad on the app it self and instead of a hovering phone maybe you can create the phone as an img inside the relevant containers and hide and show with id...
You can simply use a substring on your location.hash for get your hash tag
$(document).ready(function(){
$(".phone").hide();
var id = window.location.hash.substr(1);
if($(id) == "second"){
$(".phone").show();
}else{
$(".phone").hide();
}
});
Сan you explain please.
Why returned, only the first data attribute - "link-1.html", even if I click on the second link
<a class="project-link" href="link-1.html" data-url="link-1.html">
<a class="project-link" href="link-2.html" data-url="link-2.html">
var toUrl = $('.project-link').attr('data-url');
$('a').click(function() {
window.location.hash = toUrl;
});
The meaning of such action - my links open through Ajax, but I want to URL displayed in the browser.
I want to make it as behance, if you click on the cards portfolio, they displayed through Ajax in the same window, but it also left open the possibility of direct appeal to the links. That's why I want to URL displayed in the browser address bar
You have to get current target url by this
$('a').click(function() {
var toUrl = $(this).data('url'); // use this as current target
window.location.hash = toUrl;
});
I recommend you to use .data() when you're retrieving data attributes (only) instead of .attr()
Demo
.attr( attributeName )
Returns: String
Description: Get the value
of an attribute for the first element in the set of matched elements.
$('.project-link') matches more than one element. Therefore, $('.project-link').attr('data-url') will return the value of the data-url attribute for the first element in the set.
To solve this you have maintain the context of the clicked element as you get the attribute, and you do this by using the this keyword.
And if you have other event listeners attached to the element already and you do not want them to fire -- although ajax calls will abort when the user is redirected -- you can use event.stopImmediatePropagation():
$('a').on('click', function( event ) {
event.stopImmediatePropagation();
window.location.hash = $(this).data('url'); //this here refers to the element that was clicked.
});
$('a[data-url]').click(function() {
window.location.href = $(this).data("url");
});
You might want to try this:
$('.project-link').click(function(){
window.location.hash = $(this).data('url');
});
I am currently using OwlCarousel2 for my carousel needs. I chose OwlCarousel2 over OwlCarousel1 since it has an URL hash navigation: http://www.owlcarousel.owlgraphic.com/demos/urlhashnav.html
<div id="contestant-carousel">
<div id="poll-images" class="owl-carousel">
<?php
for($counter = 1; $counter <= 14; $counter++) {
echo "<div class='item' data-hash='$counter'><a href='" . HTTP_SERVER . "vote.php?contestant_id=$counter'><img src='/images/contestants_mobile/$counter.png' alt='$counter'></a></div>";
}
?>
</div>
</div>
Above is the PHP code I use to generate my carousel. I have fourteen images, so my code loops through all fourteen images and adds a data-hash object to each image (for the anchor navigating needs).
The following is my Javascript code:
$(document).ready(function() {
$("#poll-images").owlCarousel({
items: 1,
loop:false,
center:true,
margin:10,
lazyLoad:false,
URLhashListener:true,
onDragged:callback,
autoplayHoverPause:true,
startPosition: 'URLHash'
});
function callback(event) {
window.location.hash = event.item.index;
console.log(event.item.index);
}
});
Now, the above carousel works perfectly if the user manually adds in the hash in their URL, i.e. someurl.com/voting.php#4, this would navigate to the fourth image.
However, want I want to do is, if the url navigates to someurl.com/voting.php, as they scroll through each image, my URL would update its anchor accordingly. Why? Since if my user clicks on the image (which contains a href), and they go to the previous page, they could navigate back to the image they were looking at, instead of the default behavior of going to the first image.
According to the OwlCarousel2 API (which is actually quite different from OwlCarousel1), to get the current item, you can do this:
function callback(event) {
// Provided by the core
var element = event.target; // DOM element, in this example .owl-carousel
var name = event.type; // Name of the event, in this example dragged
var namespace = event.namespace; // Namespace of the event, in this example owl.carousel
var items = event.item.count; // Number of items
var item = event.item.index; // Position of the current item
// Provided by the navigation plugin
var pages = event.page.count; // Number of pages
var page = event.page.index; // Position of the current page
var size = event.page.size; // Number of items per page }
Specifically, using event.item.index. My code did precisely that! But I am unable to retrieve the current index! My error is: Uncaught TypeError: Cannot read property 'item' of undefined under Chrome's console.
Any help from JS gurus would be much appreciated!
I tried searching all over StackOverflow as well as the OwlCarousel2 API to see if I could do this, however, no luck.
I have also checked this thread: append /remove anchor name from current url without refresh
Found the fix here!
// jQuery method on
owl.on('changed.owl.carousel', function(property){
var current = property.item.index;
window.location.hash = current + 1;
});
OwlCarousel2 guy needs to update his API =/
Found here: Owl Carousel 2 - Get src of current slide
I have a web site on based on SkelJS that currently loads a different part of the webpage by appending an #anchor to the url like this:
Note that #blog loads the blog page, the scroll is at the top. Inside the Blog page I need to scroll to a certain article. How can I use two anchors so that something like #blog#article_x would work? I suppose I have to look for a workaround since anchoring 2 ids makes no sense, is there a work around?
Additional notes:
Note that if a change #blog to #article_x it actually goes to the desired article however if someone shares the link it won't go to the article because it will look for #article_x on the homepage, where it does not exists.
Here is a demo of the template I'm using (http://html5up.net/uploads/demos/astral/#) note how the #anchor loads the desired page.
You can use a hash that contains both page and element. Then split and then do your page load then scroll, i.e. #blog,someelement
//on page load or wherever you detect the hash
$(function(){
var hash = window.location.hash;
var ele = null;
//Detect if there is a splitable hash
if(hash.indexOf(",") != -1){
var parts = hash.split(",");
hash = parts[0];
ele = jQuery("#"+parts[1]);
}
//whatever function you do to load the blog page
loadPage(hash,ele);
});
function loadPage(page,ele){
//do page loading
$("#page").load("http://someurl.com",function(){
//if there was no second part to the hash
//this will be skipped
if(ele){
$("html,body").animate({
scrollTop: ele.offset().top
},1000);
}
});
}
JSfiddle Demo
Considering the ID of the element that you want to scroll to is myelement you can use below jquery code to smoothly scroll to it.
$("html,body").animate({scrollTop : $("#myelement").offset().top},1000);
We can scroll to specific div when it has id or class
var $id=window.location.href.split('#')[1];
$('html, body').scrollTop($("#"+$id).offset().top)
I am creating a single page layout portfolio website and one of the features I'd like to include is a fixed button that when clicked will go to the next section (portfolio piece, contact, about, whatever happens to be next) when clicked. Typically for this kind of layout I would use a smooth scroll function and then just have individual anchors targeted from different buttons but I've never tried to make one button that will do it all. Is there a way to change the target anchor of this button on every click or is there a better method for this that I'm not aware of? Apologize, I have no real code to show because I'm not sure how to approach this from the start, any suggestions would be greatly appreciated.
If I understand your question correctly, you can divide your one-pager into separate sections in equal length. Then have a fixed button on the page that scroll to the next section as you click.
i would say that you need to have an array of Targets.
and something like :
var targets = ["asd", "dsa", "123", "321"];
$("#SomeAnchor").click(function(e) {
e.preventDefault(); //prevents firing the event of the <a> tag
var currentTarget = $(this).attr('href'); //takes current anchor target
var nextTarget = null;
for (var i =0; i < Targets.length; i++) { //loop every target
if (Targets[i] === currentTarget ) { //if this is the current target, get next
if (i === Targets.length - 1) { //if i stands for the last position in Targets
nextTarget = Targets[0]; //first target again
} else {
nextTarget = Targets[i + 1]; //take next target
}
}
}
//i dont get what you want to do next, but now you can manage your targets.
//of course that it must not be targets array and it can be array of elements
// like $(".item") <- this will give you an array of elements containing class named 'item'
});
code is not tested n i wrote it here because i need to update my WebStorm first...