window.location.href.match Not Working - javascript

Here is the code:
$(function() {
var pathname = (window.location.href.match(/[^\/]+$/)[0]);
$('#menu dl dd a#toparrow').each(function() {
if ($(this).attr('href') == pathname) {
$(this).addClass('currenttop');
}
});
});
Here is a link to my website: http://bluraymoviestore.com
The purpose of the script is to make the arrow image stay on the current page, like it does when you first click to the categories.
The script works when I'm clicked on the parent page, but when I click to the next page under the same category, the script no longer works (example: works with /bluraynewreleases but not /bluraynewreleases-2625374011-rc-2-new_releases.html). What do I need to add to the code to make it work?

Your regex doesn't match anything so it throws an error when you attempt to access [0] on it. Assuming your regex is correct this should fix the issue.
$(function(){
var matches = window.location.href.match(/[^\/]+$/);
if (matches && matches.length) {
var pathname = (matches[0]);
$('#menu dl dd a#toparrow').each(function() {
if ($(this).attr('href') == pathname) {
$(this).addClass('currenttop');
}
});
}
});

Related

Check if a hash is the first element after first slash in href

I have a menu with links that may look like one of the following:
mywebsite.com/#find
mywebsite.com/about-us/#team
mywebsite.com/#social
mywebsite.com/services/#something
I want to do something only to the first and third links (the ones that don't have a subdirectory in the url path). How do I check if a # hash is the first element after the first slash in the link?
$('#menu a').click(function() {
var target = this.href;
// check if "/#" is the first thing after the domain name
});
Thank you.
The URL class that parse URLs can help you. URL.pathname property contain path of url (string after domain)
$('#menu a').click(function(e) {
if (new URL(this.href).pathname == "/"){
// Do something
}
});
More accurate mode is
$('#menu a').click(function(e) {
let url = new URL(this.href)
if (url.pathname == "/" && url.hash != ''){
// Do something
}
});
$('#menu a').click(function(e) {
e.preventDefault();
if (new URL(this.href).pathname == "/")
console.log("true");
});
a {display: block}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="menu">
mywebsite.com/#find
mywebsite.com/about-us/#team
mywebsite.com/#social
mywebsite.com/services/#something
</div>
Let's first ignore the https:// part then find the first / and hope to find a # after it.
var tests = `mywebsite.com/#find
mywebsite.com/about-us/#team
https://mywebsite.com/#social
mywebsite.com/services/#something`.split("\n");
function isMyHash(url) {
var start = url.indexOf("://") > -1 ? url.indexOf("://") + 3 : 0;
start = url.indexOf("/", start);
return (url.substring(start + 1, start + 2) == '#')
}
tests.forEach(function(test) {
console.log(test, isMyHash(test) ? "✔" : "x")
})

How to add Active class based on page URL using Javascript

Sorry if this has been addressed before, but I'm very new to JS.
I'm using an example I've found here Add Active Class to a Navigation Menu Based on URL javascript - Works only when alert is given
My altered JS is here:
$(function() {
setTimeout(function(){
var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
console.log(pgurl);
$(".mega_menu ul li a").each(function(){
if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
$(this).addClass("active");
});
}, 5000);
});
The console log is producing what appears to be the correct link however the active class is not being applied to the required class, I've included screenshots to hopefully help.console log displaying URL, NAV elements that ACTIVE class should be applied to.
Thank you in advance!
I thank everyone for your help. Below is the code that functions, and it's obvious that I have a way to go, in my understanding of JS:
$(function() {
setTimeout(function(){
var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
console.log(pgurl)
$("ul.mega_menu li a.mega_menu_with_ul").each(function(){
var _this = this;
console.log(_this)
//your condition fails here, can you check your pgurl has this value?
//old - if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
// pgurl - hardcoded 'merchandise2.asp?Merchandise_Group1_ID=8' to run the code successfully
if($(_this).attr("href") == pgurl || $(_this).attr("href") == '' ) {
$(_this).addClass("active");
console.log(_this)
}
});
}, 50); });
I believe I was running into an issue in both the way the CSS calls were structured and my understanding of how specific I needed to be to address the correct element with Javascript.
Except pgurl, there is no issue with your code.
$(function() {
setTimeout(function(){
// var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
var pgurl = window.location.pathname.replace("/","") + window.location.search; //replace first "/" and make it empty
$("#nav ul li a").each(function(){
var _this = this;
//your condition fails here, can you check your pgurl has this value?
//old - if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
// pgurl - hardcoded 'merchandise2.asp?Merchandise_Group1_ID=8' to run the code successfully
if($(_this).attr("href") == pgurl || $(_this).attr("href") == '' ) {
$(_this).addClass("active");
console.log(_this)
}
});
}, 50); });
Please note: you should not use getting and extracting the URL like this
window.location.href.substr(window.location.href.lastIndexOf("/")+1);
instead refer the easiest way to get url details
https://www.w3docs.com/snippets/javascript/how-to-get-current-url-in-javascript.html

Selecting, Deleting jQuery based on wildcard

What I would like is if there is NOT a word "link" in the href "www.1link.com" all the top classes 1-6 is changed to classdefault.
Also a different code that does the same thing except of adding "defaultclass" it removes all the classes 1-6 empty.
This is what I've tried so far and it hasn't worked
http://jsfiddle.net/yLxXn/2/
$(document).ready(function() {
if ($('a[href$="link"]')) {
// do something here
$("[class^=content]").attr("class", "classdefault");
}
});
Try something like this :
if ($('a').attr('href').indexOf('link') != -1) {
// other code
}
UPDATE
If you want this to happen if it does not contain "link", change >= to <=. As following:
For replacing all classes:
$('div').find('a').each(function(){
var hrefString = $(this).attr('href');
if (hrefString.indexOf("link") <= 0){
$('[class^=class]').attr('class', 'classdefault');
}
});
For removing all classes:
$('div').find('a').each(function(){
var hrefString = $(this).attr('href');
if (hrefString.indexOf("link") <= 0){
$('[class^=class]').removeClass();
}
});

How to detect a user clicked on an internal or external link

I need to know if users clicked on an internal or external link to alert them.
I have many internal and external links on my site.
My internal links are like this:
about
draw graph
I need to alert only when external links are clicked.
(I've included two methods here: One method uses jQuery, and the other doesn't use jQuery. Skip down to the bold heading if you don't want to use jQuery)
One way you could do this is by adding a class to each external link, and then attaching an event handler to everything in that class which raises an alert when you click the link. That's tedious, though, as you have to add the class to every external link, and it won't for user generated content.
What you can do is use jQuery, along with the CSS selector a[href^="http"], to select all the external links, and then attach an event handler that raises your alert when they're clicked:
$('a[href^="http"]').click(function() {
alert();
});
a[href^="http"] means "an a tag which has a link, and that link has to start with 'http'." So here we select all the elements which start with http - that is, every external link - and then set it so that when you click on them, an alert pops up.
Non-jQuery method
If you want to do this without jQuery, you'll want to use document.querySelectorAll('a[href^="http"]') and bind the click event of each element in the array that that function returns. That looks something like this:
var externalLinks = document.querySelectorAll('a[href^="http"]');
for (var i = externalLinks.length-1; i >= 0; i--) {
externalLinks[i].addEventListener("click", function() { alert(); }, false);
}
I had to do this from scratch on my own site so I'll just copy + paste it here for you. It came from inside one of my objects so if I left some this keywords you can remove them.
function leaving() {
var links = document.anchors || document.links || document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
if ((links[i].getAttribute('href').indexOf('http') === 0 && links[i].getAttribute('href').indexOf('fleeceitout') < 0) && (links[i].getAttribute('href').indexOf('/') !== 0 && links[i].getAttribute('href').indexOf('#') !== 0) && links[i].className.indexOf('colorbox') < 0) {
addEvent(links[i], 'click', this.action);
}
}
}
function action(evt) {
var e = evt || window.event,
link = (e.currentTarget) ? e.currentTarget : e.srcElement;
if (e.preventDefault) {
e.preventDefault();
} else {
window.location.href = link.href;
return;
}
var leave = confirm("You are now leaving the _______ website. If you want to stay, click cancel.");
if (leave) {
window.location.href = link.href;
return;
} else {
return leave;
}
}
var addEvent = function (element, myEvent, fnc) {
return ((element.attachEvent) ? element.attachEvent('on' + myEvent, fnc) : element.addEventListener(myEvent, fnc, false));
};
Replace instances of 'fleeceitout' with your sites domain name (microsoft.com, etc) and you're set.
The easiest ways are with jQuery, using a special class for external links, or by checking for "http://" in the URL.
Like this, if using a special class:
$("a.external").on("click", function() {
//de Do something special here, before going to the link.
//de URL is: $(this).attr("href")
});
And then in HTML:
<a href="http://external.link" class='external'>external link</a>
Or, you can check for http:// in the URL! Then you don't need a special class.
$('a[href=^"http://"]').on("click", function() {
//de Do something special here, before going to the link.
//de URL is: $(this).attr("href")
});
Cite: My original method of testing for "http://" was a bit slower, actually doing an indexOf test on .attr("href") so I used #Matthew's selector choice instead. Forgot about the caret route! Props to #Matthew on that, and for the non-jQuery alternative.
$(document).ready(function() {
$('a').click(function() {
var returnType= true;
var link = $(this).attr('href');
if ( link.indexOf('http') >= 0 ) {
returnType=confirm('You are browsing to an external link.');
}
return returnType;
});
});`

hasClass doesn't function as it should

I have a list of li items and would like to trigger a button click if 2 classes are found.
When a list item has 2 classes, I would like to trigger the btn with a click. Can you guys take a look for me?
The code:
<script type="text/javascript">
$(document).ready(function(){
var $html = $("#my-div ul li");
if ($html.hasClass("current") || $html.hasClass("extra")) {
$(".btn-1 a").click();}
else if ($html.hasClass("current") || $html.hasClass("extra2")) {
$(".btn-2 a").click();}
});
</script>
So one list item has class current + extra, and the other list item hasClass current + extra2.
Any idea what I am doing wrong here?
EDIT: Currently it does not work as should be.
It currently will always trigger ".btn-1" to click and does not look at the other statements. I think it just looks at the "current" class and not if also the "extra" or "extra2" class is in the same li item.
Try this:
<script type="text/javascript">
$(document).ready(function(){
var $html = $("#my-div ul li.current");
if ($html.hasClass("extra")) {
$(".btn-1 a a").click();}
else if ($html.hasClass("extra2")) {
$(".btn-2 a").click();}
});
</script>
The problem is, when you do $html.hasClass("current") || .. it would always evalutate to true and would not go to the else clause when node has a class current
You are making a comparison of a or b where you need a and b so change it to this:
<script type="text/javascript">
$(document).ready(function(){
var $html = $("#my-div ul li");
if ($html.hasClass("current") && $html.hasClass("extra")) {
$(".btn-1 a a").click();}
else if ($html.hasClass("current") && $html.hasClass("extra2")) {
$(".btn-2 a").click();}
});
</script>
Try replacing
$html.hasClass("current") || $html.hasClass("extra")
with
$html.hasClass("current") && $html.hasClass("extra")
and also
$html.hasClass("current") || $html.hasClass("extra2")
with
$html.hasClass("current") && $html.hasClass("extra2")
The original root of the problem is that you're using or (||) and not and (&&) when testing for classes. You're asking "if li has class current OR extra".
However, you can also refactor it a bit and make it a little cleaner as well:
// first, grab the <li> marked as current
var $current = $('#my-div ul li.current');
// test if we have a match and proceed
if ($current.size()){
// cache the final target selector (by initializing it to `false` we
// can later test and only execute the click when we have a match)
var target = false;
// now get in to second-level classes (can use either `.is()` or
// `.hasClass()` (thought I'd show an alternative method as well))
if ($current.hasClass('.extra')) target = '.btn-1 a a';
else if ($current.hasClass('.extra2')) target = '.btn-2 a';
// else if ($current.hasClass('...')) target = '...'; // more tests
// see if we found a match and click it
if (target) $(target).click();
}

Categories

Resources