I have a simple link with a hashtag in it. ie:
<a class="page_navigation" href="#something">click</a>
On clicking this, I would like to just end up with the 'something' part (minus the hash) in a var.
So far I have
$('.page_navigation').click(function(e)
{
e.preventDefault();
var href = $(this).attr('href');
});
Obviously I just end up with '#something' in my href var with the above code, and I understand I could do some kind of regex (not sure how yet) to strip the #, but I wonder if there is an easier way to access this part of the href I'm unaware of, without having to go through some find and replace code.
Any ideas?
Note: I also know I could store the 'something' in a data tag, but I'm trying to keep this code as DRY as possible.
If you know it has a # in it, you can use this:
$('.page_navigation').click(function(e)
{
e.preventDefault();
var hash = this.href.replace(/^.*#/, "");
});
If you don't know whether it has one it it or not, you can use this:
$('.page_navigation').click(function(e)
{
e.preventDefault();
var hash = "";
if (this.href.indexOf("#") {
hash = this.href.replace(/^.*#/, "");
}
});
In HTML5, you could use:
this.hash
but that is only for the latest browsers.
var theHash = $(this).prop("hash").substr(1);
Related answer to another question
Demo http://jsfiddle.net/UR3XN/
code
$('.page_navigation').click(function(e)
{
e.preventDefault();
var href = $(this).attr('href');
var equalPosition = href.indexOf('#'); //Get the position of '#'
var withouthash = href.substring(equalPosition + 1);
alert(withouthash);
});
You don't need regular expressions for this. You can simply do
var fragment;
if (window.location.hash) {
fragment = window.location.hash;
}
Note that this will pick up the # symbol as well. So,
fragment = "#something"
If you don't want the # symbol, use substring like this:
fragment = window.location.hash.substring(1)
If you want to pick out the hash fragment from an anchor tag, you can do this:
var link = $('#yourAnchor').attr('href');
var fragment;
if (link.indexOf("#") !== -1) {
fragment = link.substr(link.indexOf("#") + 1);
}
Related
on my homepage, I currently have a jQuery that adds a class (in this case an underline) to the link element. This works great and is based on comparing the url (url/firstsubmenu) in the browser with the href of the link element.
However as soon as I go to a child of that link element (url/firstsubmenu/secondsubmenu), the class is gone. I have tried to split the url so that the jQuery always looks for the parent but I just can't solve it. Can you help me?
Could it be solved by adding another code, like maybe "if (this).children().length > 0 ?"
Here is my jQuery:
var cururl = window.location.href;
cururl = cururl.split('#')[0];
jQuery("a.rs-layer").each(function(){
if(jQuery(this).attr('href')=== cururl){
jQuery(this).addClass("current-slider-menu");
}
});
EDIT: I am new to this, and I have tried so many different codes, googled for hours. I now know that I can only write JavaScript in my CMS. That is, I cannot use jQuery operators such as, for example, $.
Try this,
Change the class/selectors as per your requirement. This will add a unique class in the li element, now you can style this using css.
$(document).ready(function() {
$(".main_menu li").removeClass('current-slider-menu');
$(".main_menu li>a").filter(function(){
return this.href == location.href.replace(/#.*/, "");
}).parent("li").addClass("current-slider-menu");
});
You're definitely on the right track.
You can grab the currentURL (before the anchor #):
const currentURL = window.location.href.split('#')[0];
Then you can split the currentURL into its constituent folders:
const currentURLArray = currentURL.split('/');
Then, separately, you can grab all the myLinks:
const myLinks = [...document.querySelectorAll('a.rs-layer')];
And finally you can cycle through myLinks and if the name of the folder you want to match does match the name of the equivalent folder in the currentURL, then you can add the .current-slider-menu class:
for (myLink of myLinks) {
if (myLink.href.split('/')[1] === currentURLArray[1]) {
myLink.classList.add('current-slider-menu');
}
}
Complete Example:
const currentURL = window.location.href.split('#')[0];
const currentURLArray = currentURL.split('/');
const myLinks = [...document.querySelectorAll('a.rs-layer')];
for (myLink of myLinks) {
if (myLink.href.split('/')[1] === currentURLArray[1]) {
myLink.classList.add('current-slider-menu');
}
}
EDITED
try this
var cururl = window.location.href;
jQuery("rs-layer[id|='"+cururl.split('/')[3]+"'] , .rs-layer[href='"+cururl+"']").each(function(){
jQuery(this).addClass("current-slider-menu");
});
I solved it like this instead, skipping the whole idea with text-decoration.
I added an arrow. Finished.
JS:
var url = window.location.href;
var msg = document.getElementById('current-menu-item-arrow');
if( url.search( 'my-word' ) > 0 ) {
msg.style.display = "block";
}
CSS:
#current-menu-item-arrow {display:none;}
I am trying get all HTML links in a website's body section within a string and replace them to another link.
Tried something like this but did not work:
var search = "https://www.cloudflare.com/5xx-error-landing?utm_source=error_footer";
var replacement = "https://example.com/";
document.body.innerHTML = document.body.innerHTML.split(search).join(replacement)
Where "https://www.cloudflare.com/5xx-error-landing?utm_source=error_footer" is the link I want to replace and "https://example.com/" is the link that I want to replace with.
How about this:
$("[href='your link']").attr("href","new link");
Here is a solution with plain javascript as per your question
document.querySelectorAll("[href='" + search + "']").forEach(function(el){
el.href = replacement );
});
If you want to use jQuery, as you tagged, follow the answer of Nir Tzezana
$('body').find('a').each(function(){
$(this).attr('href','your_new_link');
});
or for different href:
$('body').find('a').each(function(){
var ahref = $(this).attr('href');
if ( ahref == 'your_old_link') { /// or ahref.indexOf("your_old_link") >= 0
$(this).attr('href','your_new_link_1');
}else{
$(this).attr('href','your_new_link_2');
}
});
Just use
$("body a[href='https://www.cloudflare.com']").attr("href","https://example.com/");
I have jQuery code that "colors the active menu item" in the my navigation menubar.
I found it online, and I find little of it hard to understand.
/// <reference path="jquery-1.10.2.js" />
$(document).ready(function () {
SetNavigation();
});
function SetNavigation() {
var pathName = window.location.pathname;
var path = window.location.pathname;
path = path.replace(/\/$/, "");
path = decodeURIComponent(path);
$("#topnavnmenu a").each(function () {
var href = $(this).attr('href');
if (path.substring(0, href.lenght) == href) {
$(this).closest('li').addClass("active");
}
})
}
Questions to the above displayed code:
Why is he doing that:
path = path.replace(/\/$/, "");
Should he not make sure before Comparison of Url and
that <a href = " " is taken before parameters
IF yes, how to write code for it ?
$("#topnavnmenu a").each(function () {
var href = $(this).attr('href');
if (path.substring(0, href.lenght) == href) {
$(this).closest('li').addClass("active");
}
})
Why is he doing that: path = path.replace(//$/, "");
The regex \/$ in :
path.replace(/\/$/, "");
Used just to remove (replace by empty) the last slash / in the path.
Example :
console.log('www.website.com/'.replace(/\/$/, "")); //Remove last slash
console.log('www.website.com/page1/'.replace(/\/$/, "")); //Remove last slash
console.log('www.website.com/page2'.replace(/\/$/, "")); //No slash no change
Should he not make sure before Comparison of Url and that
Not 100% sure what u mean by this, but the way "he" has coded this if even if href or comparison is 'undefined' the execution will not stop.
Function simply gives active class to all matching menu items.
For the function it dosent matter if all or none match. Since function executed in document ready its safe to assume all href attributes are already existing and therefore they will be found.
Can anyone see where I going wrong here, I'm trying to get the last characters after the ?p= in a link and put in a varaible, but the code I'm using returns /.
My code is:
$("#dvPartial").on('click', '.dvPagerCities a', function (event) {
alert('click detected');
var city = ($('input#hdnCountry').val());
alert(city);
var link = $('a').attr('href');
//var getEqualPosition = link.indexOf('?p='); //Get the position of '='
var getEqualPosition = link.indexOf('='); //Get the position of '='
var number = link.substring(getEqualPosition + 1); //Split the string and get the number.
My link is
»
I think what is happening is its picking up the 1st = .
My theory is this.
1) Detect the click event
2) Get the link that caused the event
3) Extract the value of p,
p can be 1 diget, 2 digets or 3 digets.
Any help would be appreciated, as it seems no sooner do I solve 1 problem then another arises.
Thanks
George
Assuming that p is the only parameter in the URL you can simply split by the = sign:
$("#dvPartial").on('click', '.dvPagerCities a', function (event) {
var city = $('input#hdnCountry').val();
var number = $(this).attr('href').split('=')[1];
});
The problem is this part:
var link = $('a').attr('href');
That does not select the link that was clicked, unless you happen to be clicking the very first link present in the HTML of the page. What that will do is select all <a> elements, then return the href attribute of the first one.
Inside your event handler, you want to use this to refer to the link that was clicked:
var link = $(this).attr('href');
// or simply
var link = this.href;
Try with this:
link.split('?p=')[1]
String s = "Jecy penny ? like sears";
String[] arr = s.split("\\?");
Added \\ before ?, as ? has a special meaning
String res = arr[0];
May be you are wrong at escape character for ' ? '
check this link Remove all characters after a particular character
Try this: http://jsfiddle.net/7atyG/1/
$(document).on('click', '.dvPagerCities a', function (ev) {
ev.preventDefault();
var link = $(this).attr('href');
var Linkval = link.substr(link.indexOf('=') + 1);
alert(Linkval);
});
Let's say the window's location is on htt://stackoverflow.com/index.php, I want to remove an element in the index page with jQuery. This is what I have and it's not working:
$(document).ready(function() {
var location = window.location;
var locQuery = /index/i;
if (location.match(locQuery)) {
$('.someClass').removeClass();
}
});
You are only removing it's class, so for example
<div class="someclass"></div>
will change into
<div></div>.
try
$('.someClass').remove();
I found the problem. window.location is an object so the .match method couldn't match anything from the regex. I had to use the .href property of window.location to get a match.
var location = window.location.href;
var locQuery = /index/i;
if (location.match(locQuery)) {
$('.someClass').remove();
}
I hope I use the right terms. I'm new to JavaScript.