Attempting to remove anchor tags from the URL - html

Situation: I want to remove the anchor tags ( #tag ) from the end of the URL
What I have tried: I have been following "https://www.finsweet.com/hacks/15/" and "https://stackoverflow.com/questions/34175285/removing-anchor-tags-from-url". Its not working out very well though.
Code:
My snippet from the top nav bar
<ul class="nav">
<li class="scroll-to-section">
Home
</li>
</ul>
My use of Id
<div class="main-banner header-text" id="top">
Maybe the way i approached the edits to the navigation bar is wrong.. but im not sure what i need to to do to achieve the goal. Or how I used the classes and IDs is possibly incorrect?
--- Edit 1 ---
this is the snipper of the script im attempting to use to remove the anchor tag from the URL bar of a brower.
$("#js-anchor").click(function (evt) {
evt.preventDefault();
var anchor = $(this).text();
$("html, body").animate(
{
scrollTop: $("#" + anchor).offset().top,
},
1500
);
});
And the html im looking at
<li class="scroll-to-section">
<a id="js-anchor" href="#testimonials" class="active"
>staff</a>
</li>
The experment on it is here:
https://the-md.studio/indexhash.html
EDIT2
My new attempt
<li class="scroll-to-section">
Home
</li>
JS
$(document).ready(function () {
// get the anchor link buttons
const menuBtn = $(".scroll-to");
// when each button is clicked
menuBtn.click(() => {
// set a short timeout before taking action
// so as to allow hash to be set
setTimeout(() => {
// call removeHash function after set timeout
removeHash();
}, 5); // 5 millisecond timeout in this case
});
// removeHash function
// uses HTML5 history API to manipulate the location bar
function removeHash() {
history.replaceState(
"",
document.title,
window.location.origin + window.location.pathname + window.location.search
);
}
});

Just saw this Q. I guess this is what you tried to ask:
// first: get the full url
var hash_url = window.location.href;
// second: simply do a split
// can't go wrong here, because url's that show content are always in correct format
hash_url = hash_url.split('#'); var clean_url = hash_url[0];
alert(clean_url);
There's your clean url!

Related

JQuery populate div with link content but also need to move (like anchor link) to area where div located

I have unordered list of links. Using JQuery, when clicked, the link's contents (a div with image and text) are loaded into the section specified. This all works beautifully. But I'm wondering how to also get the onclick function to move the view to the div's location on the page similarly to how anchor tag works. Here is the site where you can see the div being populated, but not moving down to view it. https://www.thecompassconcerts.com/artists.php
My JQuery knowledge is not awesome (I'm being generous).
I followed Osama's suggestion to add event listener and I got almost correct results. Upon first click...contents are loaded but do not move. But on every successive click, it functions perfectly: Contents loaded and move to div (like an anchor link) works! BUT...not on Safari or Mobile Safari.
Here is my jQuery. I assume if first click is not working that I must add listener before the first click?? Can the event listeners be added on page load BEFORE the function to prevent default click, etc.?
<script>
// BEGIN FUNCTION TO CAPTURE AND INSERT CONTENT
$(document).ready(function () {
// PREVENT DEFAULT LINK ACTION
$('.bio').click(function (e) {
e.preventDefault();
// ADD LISTENER TO EACH ITEM BY CLASS
var list = document.getElementsByClassName("bio");
for (let i = 0; i < list.length; i++) {
list[i].onclick = moveToDiv;
}
// FUNCTION TO MOVE TO LOCATION
function moveToDiv() {
document.location = "#performbio";
}
// STORE the page contents
var link = $(this).attr("href");
// load the contents into #performbio div
$('#performbio').load(link);
});
});
</script>
Here is the HTML with links in unordered list
<!-- CONTRIBUTING ARTISTS LIST AND BIOS -->
<section id="artists">
<h2>Contributing Artists</h2>
<ul class="cols">
<li><a class="bio" href="performers/first-last.html">First Last</a></li>
<li><a class="bio" href="performers/first-last.html">First Last</a></li>
<li><a class="bio" href="performers/first-last.html">First Last</a></li>
</ul>
</section>
Here is HTML of Section where code is being inserted by function
<!-- Performer Bios Dynamically updated -->
<section id="performbio">
</section>
Here is div contents that are being inserted
<div class="artistbio">
<p class="artistname">First Last</p>
<img class="artistimg" src="performers/img/name.jpg">
<p>lots of text here</p>
</div>
If I understand it right, you want to scroll to the section where the details appear on clicking any item in the list but through js and not HTML. In that case, you would add an onclick listener on to the list elements like so:
listElement.onclick = moveToDiv;
The function:
function moveToDiv() {
document.location = "#performbio";
}
A simple way to add a listener to all of the elements:
var list = document.getElementsByClassName("bio");
for (let i = 0; i < list.length; i++) {
list[i].onclick = moveToDiv;
}
For the edited post, you need to move the function definition out of the document.ready function. you would change the script to:
// FUNCTION TO MOVE TO LOCATION
function moveToDiv() {
document.location = "#performbio";
}
$(document).ready(function () {
// PREVENT DEFAULT LINK ACTION
$('.bio').click(function (e) {
e.preventDefault();
// ADD LISTENER TO EACH ITEM BY CLASS
var list = document.getElementsByClassName("bio");
for (let i = 0; i < list.length; i++) {
list[i].onclick = moveToDiv;
}
// STORE the page contents
var link = $(this).attr("href");
// load the contents into #performbio div
$('#performbio').load(link);
});
});
Another Solution: Using scrollIntoView
First, get all the elements into a variable using querySelectorAll
var elements = document.querySelectorAll(".bio");
Then create a function, for the scrolling part:
function scroll(element) {
element.scrollIntoView();
}
Then just add the onclick listener:
for (let i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', function() {
scroll(elements[i]);
});
}
I found it very frustrating to try to accomplish these two tasks so instead of a jQuery solution I opted for a CSS solution.
I populated my DIV with all the php includes, gave them unique id's for the anchors to work and then used CSS to hide them by default until clicked and it works like a charm....shows only what I need to show and goes there like an anchor is supposed to.
I must thank Ghost for all of your help and efforts to try and solve this via jQuery. You were very kind and generous.
Here is the code I used:
My collection of links.
<li><a class="bio" href="#artist-name1">Name 1</a></li>
<li><a class="bio" href="#artist-name2">Name 2</a></li>
which anchors to these divs
<div class="bio-container" id="artist-name1">
<?php include('performers/name-lastname.html'); ?>
</div>
<div class="bio-container" id="artist-name2">
<?php include('performers/name-lastname.html'); ?>
</div>
Then I use this CSS to hide those divs until the anchors are clicked.
I'm using [id*="artist-"] to target only links with such text...very easy. Not ideal for a massive list...but mine is not so large so it will do for this situation.
[id*="artist-"] {display: none;}
[id*="artist-"]:target {display: block;}

Pivot icons are not clickable

I have a pivot element in my page, it's work but when I want to change text by icons, they become not clickable and we have to click in the grey part. Do you know how make them clickable ?
In green the clickable part and in red not clickable part.
Part of my code :
<li id="listPivotAccount" class="ms-Pivot-link is-selected " data-content="account" title="Mon compte" tabindex="1">
<i style="" class=" ms-Icon ms-Icon--Accounts" aria-hidden="true"></i>
</li>
You can check the code here
For the record, I have never used SharePoint, so there may be a more elegant solution.
You can fix this behaviour by adding this vanilla JavaScript after your current JavaScript:
// select all icons
var msIcons = document.querySelectorAll(".ms-Icon");
// loop all icons
for (var i = 0; i < msIcons.length; i++) {
// add a click event to the nearest element with class "ms-Pivot-link"
msIcons[i].closest(".ms-Pivot-link").addEventListener("click", function() {
this.click();
});
}
jQuery Example of the above code:
$(".ms-Icon").on("click", function() {
$(this).closest(".ms-Pivot-link").click();
});
var Dropdown = new Class({
initialize: function() {
var e = this;
document.addEvents({
"click:relay(.windowLabel, .dropdown a.dropdownTrigger)": function(t, n) {
t && (t.preventDefault(),
t.stopPropagation()), // issue is here
e.showPopover.call(e, n)
}
}),
document.body.addEventListener("click", function(t) {
e.hideOutside.call(e, t)
})
},
// ...
})
Problem is in preventing propagation of events, and as result all nested elements shouldn't emit what you need.
What is the solution?
You can try add the icon in different way (for example using :before, :after)
The simple way to fix it is to trigger the pivot with a click. So if you use JQuery :
$('.ms-Icon').click(function () {
var pivot = $(this).closest(".ms-Pivot-link");
pivot.click();
});
Short and compatible with IE > 9

Ahref links/anchors moving page down vertically preventDefault();

This is no doubt very basic HTML, but I have a problem with some anchor tags. I have a page with three overlapping tabs. You click on the tab and the contents come to the front. THe problem is that the page moves vertically down so that the tab is at the top of the page (they are halfway down usually).
Attached is my script to perform the function, as well as a version of the HTML associated.
I think I need to use preventDefault(); somewhere, but not sure where. Any ideas appreciated.
<!--Javascript function to brings tabs to the front-->
<script type="text/javascript">
$(document).ready(function () {
$("div.tab-headers>a").click(function () {
// Grab the href of the header
var _href = $(this).attr("href");
// Remove the first character (i.e. the "#")
_href = _href.substring(1);
// show this tab
tabify(_href);
});
tabify();
});
function tabify(_tab) {
// Hide all the tabs
$(".tab").hide();
// If valid show tab, otherwise show the first one
if (_tab) {
$(".tab a[name=" + _tab + "]").parent().show();
} else {
$(".tab").first().show();
}
}
// On page load...
$(document).ready(function () {
// Show our "default" tab.
// You may wish to grab the current hash value from the URL and display the appropriate one
// tabify();
});
</script>
My HTML is:
<div class="glossary">
<div class="tab-headers">
</div>
<!--Tab 1-->
<div class="tab">
<a name="tab1"></a>
contents 1 here
</div>
<!--Tab 2-->
<div class="tab">
<a name="tab2"></a>
contents 2 here
</div>
<!--Tab 3-->
<div class="tab">
<a name="tab3"></a>
contents 3 here
</div>
</div>
I believe the preventDefault() should go here:
$("div.tab-headers>a").click(function(e){
e.preventDefault();
....
Notice the added (e) after the function. So that would result in the following code:
<!--Javascript function to brings tabs to the front-->
<script type="text/javascript">
$(document).ready(function () {
$("div.tab-headers>a").click(function (e) {
e.preventDefault(); // normal behavior is stopped
// Grab the href of the header
var _href = $(this).attr("href");
// Remove the first character (i.e. the "#")
_href = _href.substring(1);
// show this tab
tabify(_href);
});
tabify();
});
function tabify(_tab) {
// Hide all the tabs
$(".tab").hide();
// If valid show tab, otherwise show the first one
if (_tab) {
$(".tab a[name=" + _tab + "]").parent().show();
} else {
$(".tab").first().show();
}
}
// On page load...
$(document).ready(function () {
// Show our "default" tab.
// You may wish to grab the current hash value from the URL and display the appropriate one
// tabify();
});
</script>

jQuery Deep linking, load content from div in other page issues

I was able to set up a function where upon clicking the nav link it loads the "#content" div from the appropriate page into the "#content" div on the current page. The issue arose when I tried implementing deep linking with the address plugin. I can't seem to figure out how to get it to load just the "#content" div from a page.
You can see it live here: www.theeastcoastclassic.com/index1.html
The bottom nav still has the original .load function, the top is using the deep linking function.
Here's my .js file:
// Deep Linking
function loadURL(url) {
console.log("loadURL: " + url);
$("#content").load(url);
}
$.address.init(function(event) {
console.log("init: " + $('[rel=address:' + event.value + ']').attr('href'));
}).change(function(event) {
$("#content").load($('[rel=address:' + event.value + ']').attr('href'));
console.log("change");
})
$('ul#topNav a').live('click', function(e){
$.scrollTo('#content', 'slow');
$("#content").hide();
loadURL($(this).attr('href').fadeIn("6000"));
e.preventDefault();
});
// Top Nav Hijax
/* $("ul#topNav a").live("click",function(e) {
$.scrollTo('#content', 'slow');
var url = $(this).attr("href") + " #content";
$("#content").hide().load(url).fadeIn("6000");
e.preventDefault();
}); */
// Bot Nav Hijax
$("ul.bNav a").live("click",function(e) {
$.scrollTo('#content', 'slow');
var url = $(this).attr("href") + " #content";
$("#content").hide().load(url).fadeIn("6000");
e.preventDefault();
});
//Equal Height Columns
$(document).ready(function() {
$("div .col3").equalHeights();
});
This is the abridged HTML:
<ul id="topNav">
<li>
Home
</li>
<li>
Schedule
</li>
<li>
Lodging
</li>
<li>
Sponsors
</li>
<li>
Directions
</li>
<li>
Contact
</li>
</ul>
<div id="content" class="clearfix">
</div>
Also if you have any tips about the equalHeights columns please let me know, it seems as though this plugin is very simple but appears differently on each browser, I'm getting a lot of scrollbars.
You need to add a change() function, so if the address changes this will be executed:
$.address.change(function(event) {
// your loading logic goes here
});

Make anchor links refer to the current page when using <base>

When I use the HTML <base> tag to define a base URL for all relative links on a page, anchor links also refer directly to the base URL. Is there a way to set the base URL that would still allow anchor links to refer to the currently open page?
For example, if I have a page at http://example.com/foo/:
Current behaviour:
<base href="http://example.com/" />
bar <!-- Links to "http://example.com/bar/" -->
baz <!-- Links to "http://example.com/#baz" -->
Desired behaviour:
<base href="http://example.com/" />
bar <!-- Links to "http://example.com/bar/" -->
baz <!-- Links to "http://example.com/foo/#baz" -->
I found a solution on this site: using-base-href-with-anchors that doesn't require jQuery, and here is a working snippet:
<base href="https://example.com/">
/test
Anchor
Or without inline JavaScript, something like this:
document.addEventListener('DOMContentLoaded', function(){
var es = document.getElementsByTagName('a')
for(var i=0; i<es.length; i++){
es[i].addEventListener('click', function(e) {
e.preventDefault()
document.location.hash = e.target.getAttribute('href')
})
}
})
Building upon James Tomasino's answer, this one is slightly more efficient, solves a bug with double hashes in the URL and a syntax error.
$(document).ready(function() {
var pathname = window.location.href.split('#')[0];
$('a[href^="#"]').each(function() {
var $this = $(this),
link = $this.attr('href');
$this.attr('href', pathname + link);
});
});
A little bit of jQuery could probably help you with that. Although base href is working as desired, if you want your links beginning with an anchor (#) to be totally relative, you could hijack all links, check the href property for those starting with #, and rebuild them using the current URL.
$(document).ready(function () {
var pathname = window.location.href;
$('a').each(function () {
var link = $(this).attr('href');
if (link.substr(0,1) == "#") {
$(this).attr('href', pathname + link);
}
});
}
Here's an even shorter, jQuery based version I use in a production environment, and it works well for me.
$().ready(function() {
$("a[href^='\#']").each(function() {
this.href = location.href.split("#")[0] + '#' + this.href.substr(this.href.indexOf('#')+1);
});
});
You could also provide an absolute URL:
<base href="https://example.com/">
test
Rather than this
test
I'm afraid there is no way to solve this without any server-side or browser-side script. You can try the following plain JavaScript (without jQuery) implementation:
document.addEventListener("click", function(event) {
var element = event.target;
if (element.tagName.toLowerCase() == "a" &&
element.getAttribute("href").indexOf("#") === 0) {
element.href = location.href + element.getAttribute("href");
}
});
<base href="https://example.com/">
/test
#test
It also works (unlike the other answers) for dynamically generated (i.e. created with JavaScript) a elements.
If you use PHP, you can use following function to generate anchor links:
function generateAnchorLink($anchor) {
$currentURL = "//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$escaped = htmlspecialchars($currentURL, ENT_QUOTES, 'UTF-8');
return $escaped . '#' . $anchor;
}
Use it in the code like that:
baz
To prevent multiple #s in a URL:
document.addEventListener("click", function(event) {
var element = event.target;
if (element.tagName.toLowerCase() == "a" &&
element.getAttribute("href").indexOf("#") === 0) {
my_href = location.href + element.getAttribute("href");
my_href = my_href.replace(/#+/g, '#');
element.href = my_href;
}
});
My approach is to search for all links to an anchor, and prefix them with the document URL.
This only requires JavaScript on the initial page load and preserves browser features like opening links in a new tab. It also and doesn't depend on jQuery, etc.
document.addEventListener('DOMContentLoaded', function() {
// Get the current URL, removing any fragment
var documentUrl = document.location.href.replace(/#.*$/, '')
// Iterate through all links
var linkEls = document.getElementsByTagName('A')
for (var linkIndex = 0; linkIndex < linkEls.length; linkIndex++) {
var linkEl = linkEls[linkIndex]
// Ignore links that don't begin with #
if (!linkEl.getAttribute('href').match(/^#/)) {
continue;
}
// Convert to an absolute URL
linkEl.setAttribute('href', documentUrl + linkEl.getAttribute('href'))
}
})
You can use some JavaScript code inside the tag that links.
<span onclick="javascript:var mytarget=((document.location.href.indexOf('#')==-1)? document.location.href + '#destination_anchor' : document.location.href);document.location.href=mytarget;return false;" style="display:inline-block;border:1px solid;border-radius:0.3rem"
>Text of link</span>
How does it work when the user clicks?
First it checks if the anchor (#) is already present in the URL. The condition is tested before the "?" sign. This is to avoid the anchor being added twice in the URL if the user clicks again the same link, since the redirection then wouldn't work.
If there is sharp sign (#) in the existing URL, the anchor is appended to it and the result is saved in the mytarget variable. Else, keep the page URL unchanged.
Lastly, go to the (modified or unchanged) URL stored by the mytarget variable.
Instead of <span>, you can also use <div> or even <a> tags.
I would suggest avoiding <a> in order to avoid any unwanted redirection if JavaScript is disabled or not working, and emulate the look of your <a> tag with some CSS styling.
If, despite this, you want to use the <a> tag, don't forget adding return false; at the end of the JavaScript code and set the href attribute like this <a onclick="here the JavaScript code;return false;" href="javascript:return false;">...</a>.
From the example given in the question. To achieve the desired behavior, I do not see the need of using a "base" tag at all.
The page is at http://example.com/foo/
The below code will give the desired behaviour:
bar <!-- Links to "http://example.com/bar/" -->
baz <!-- Links to "http://example.com/foo/#baz" -->
The trick is to use "/" at the beginning of string href="/bar/".
If you're using Angular 2 or later (and just targeting the web), you can do this:
File component.ts
document = document; // Make document available in template
File component.html
<a [href]="document.location.pathname + '#' + anchorName">Click Here</a>