Go To Anchor on Load ( if else statement) - javascript

Hi I have a page that navigates using anchors. On load the index page (A) needs to jump to anchor. Fine I can do this with on load function but coming back to the page A from page B I want to jump to a different anchor. I have this working:
<!-- go to Anchor -->
<script type="text/javascript">
function goToAnchor() {
var urllocation = location.href;
if(urllocation.indexOf("#top") > -1){
window.location.hash="top";
} else {
window.location.hash="middle";
}
}
</script>
#middle is the anchor to use when coming from a link that contains no anchor (or from typing the address into the url bar). I want to add three more 'if's'. I am fairly new at js so bear with me if I am doing something silly. I tried this:
function goToAnchor() {
var urllocation = location.href;
if(urllocation.indexOf("#right") > -1){
window.location.hash="right";
} else {
window.location.hash="middle";
}
if(urllocation.indexOf("#bottom") > -1){
window.location.hash="bottom";
} else {
window.location.hash="middle";
}
if(urllocation.indexOf("#left") > -1){
window.location.hash="left";
} else {
window.location.hash="middle";
}
But not joy, the js breaks and no longer goes to #middle on page load.
I tried a wild card approach:
function goToAnchor() {
var urllocation = location.href;
if(urllocation.indexOf("#.") > -1){
window.location.hash=".";
} else {
window.location.hash="middle";
}
}
Again, no joy.
Any help please.. thanks kindly

I am not quite sure I understand the effect you are trying to achieve (since window.location.hash should already contain the hash part of your url), but your code should probably rather be
function goToAnchor() {
var urllocation = location.href;
if (urllocation.indexOf("#right") > -1) {
window.location.hash = "right";
} else if (urllocation.indexOf("#bottom") > -1) {
window.location.hash = "bottom";
} else if(urllocation.indexOf("#left") > -1) {
window.location.hash = "left";
} else {
window.location.hash = "middle";
}
}
I am also guessing that your 'wild card' approach is meant to use regular expressions:
function goToAnchor() {
var urllocation = location.href;
var hashMatch = urllocation.match(/#(.*)/)
if (hashMatch){
window.location.hash = hashMatch[1];
} else {
window.location.hash = "middle";
}
}
Again, I don't quite see what effect this code should have, since window.location.hash will probably have the same value before and after the assignment.

If you just want to go back to the hash in the URL, have you tried something like this?
var hash = window.location.hash || "middle"; //Get current hash or default to "middle" if no hash is currently set
window.location.hash = +new Date() + ""; //Remove the hash and set it to some random value
window.location.hash = hash; //Set to the old hash

Related

Set selected navigation option using window.location

I have a theme that sets the selected left navigation option based on what URL you are visiting. However, it breaks if the is a variable attached to the URL, for example www.test.com/abc.aspx?delete=1. The URL www.test.com/abc.aspx works fine and sets the link ABC to active.
I have tried to modify the code to cut off everything after and including ?, but it won't work as intended (nothing in the NAV is selected).
ORIGINAL CODE:
$(function () {
var url = window.location;
var element = $('ul#sidebarnav a').filter(function () {
return this.href == url;
}).addClass('active').parent().addClass('active');
while (true) {
if (element.is('li')) {
element = element.parent().addClass('in').parent().addClass('active');
}
else {
break;
}
}
});
MY EDITED CODE:
$(function () {
var url = window.location.toString();
var url_fix = url.split('?');
var element = $('ul#sidebarnav a').filter(function () {
return this.href == url_fix[0];
}).addClass('active').parent().addClass('active');
while (true) {
if (element.is('li')) {
element = element.parent().addClass('in').parent().addClass('active');
}
else {
break;
}
}
});
I think it is the line with "return this.href == url_fix[0];" that is the culprit.
SOLUTION (what I came up with after reading the comments, thanks guys):
$(function () {
var url = location.href.split("/").slice(-1).toString();
var url_fix = url.split('?');
var element = $('ul#sidebarnav a').filter(function () {
return $(this).attr("href") == url_fix[0];
}).addClass('active').parent().addClass('active');
while (true) {
if (element.is('li')) {
element = element.parent().addClass('in').parent().addClass('active');
}
else {
break;
}
}
});
Try comparing pathnames instead.
var element = $('ul#sidebarnav a').filter(function () {
return this.pathname == location.pathname;
}).addClass('active').parent().addClass('active');
For example on this page location.pathname returns:
"/questions/48234042/set-selected-navigation-option-using-window-locaiton/48234196"
and does not include location.hash or location.search
I used the answer by #vbguyny to solve the issue. Had to add location.href.split("/").slice(-1).toString(); to get the actual page name, but after that it worked fine. Thanks!

jQuery check if URL contains string

I have this code
events.on('loaded', function() {
$('.server_details .start button').click();
});
but I only want it to run if the end of the URL is &autoconnect, can someone show example of how to do this?
Example URL http://www.example.com:7778&autoconnect
You can get the url with window.location.href
and then check that using indexOf:
events.on('loaded', function() {
if (window.location.href.indexOf("&autoconnect") > -1) {
$('.server_details .start button').click();
}
});
You say "I only want it to run if the end of the URL is &autoconnect"
I say
var url = 'http://www.example.com:7778/&autoconnect';
var param = '&autoconnect';
var valid = url.indexOf(param) == url.length - param.length;
If there is a possibility that there may be other parameters as well...
var url = 'http://www.example.com:7778/&autoconnect&alsovalid';
var param = '&autoconnect';
var valid = url.indexOf(param) >= 0;
This would be more correct I suppose.
$(window).on('load', function () {
if (window.location.href.indexOf('url-content') > -1) {
// Your function do be executed
}
});

continuously check URL until string is present, run javascript code when found

i need some help with this code. i want to read the current URL, and when the URL contains "#_ThankYou" in it, I want to add a new to an existing on the page and that div contains some javascript that will display an ad from an ad vendor. i have the following but i think i might be caught in an infinite loop. not sure i coded this correctly. anyone have good suggestions?
<script type="text/javascript">
window.eddyCookieCount = 0;
window.eddyNumberAttempts = 0;
window.myInterval = setInterval(function() {
if (window.location.href.indexOf("#_ThankYou") > window.eddyCookieCount) {
jQuery('div.thankyou-container').append('<div>' + vm_load({
"displayId": "12584", // Numeric unique ad display Id
"publisherId": "33927", // Publisher ID
"campaign": "9380", // Numeric Publisher Campaign Id
"maxResults": "3",
"areaofstudy": JSON.parse(jQuery.cookie('CategorySubCategorySpecialty')).CATEGORIES[0].text.replace('Business','1').replace('Criminal Justice & Legal','3').replace('Education','5').replace('Fine Arts & Design','2').replace('Health & Medicine','8').replace('Liberal Arts & Humanities','5').replace('Math, Science & Engineering','9').replace('Public Affairs & Social Sciences','13').replace('Religious Studies','5').replace('Technology','9').replace('Vocational Training',''),
"md": "1"
}) + '</div>');
window.eddyNumberAttempts++;
if (window.eddyNumberAttempts > 60) {
window.eddyCookieCount = jQuery.cookie('CategorySubCategorySpecialty').length;
window.eddyNumberAttempts = 0;
}
}
else if (jQuery.cookie('CategorySubCategorySpecialty').length < window.eddyCookieCount) {
window.eddyCookieCount = jQuery.cookie('CategorySubCategorySpecialty').length;
}
}, 50);
</script>
There is no need to do an interval to watch for the hash to be added.
$(window).on('hashchange', function() {
if (window.location.search === "#_ThankYou") {
}
});
In your code, I do not see you ever cancelling the interval when you are in the state when the url is changed so it keeps firing. you need to cancel it.
window.clearInterval(window.myInterval)
It worked for me, where I have to check a token in the URL on view change.
The way I worked is below code, which doesn't seem good to use, but it is worked on selector basis:
$('.nav ul li a').click(function() {
setTimeout(changeurl, 4000);
});
function changeurl(title, newurl) {
if (window.location.hash == '') {
return window.location.hash = '#/dashboard';
}
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.hash;
if (history.pushState) {
window.history.pushState({path:newurl},'',newurl);
}
}
Finally, I modified the code as such:
var token = window.location.search;
$(window).on('hashchange', function() {
if (window.location.search === token) {
setTimeout(changeurl, 4000);
}
});

Chrome extension not finding current tab?

In my code, I want to check if on the page you are on, if certain requirements are met with the url, do something
It is saying it cannot get the toLowerCase of undefined
this is my code, thanks
Also, I do have tab permissions in the manifest
This file runs in the background, I want it to execute for every page you open
var names = ['hunter5deer', 'pielovingcat', '199MS', 'harrdy']
$(function() {
for (i=0;i<names.length;i++) {
var currentPage;
chrome.tabs.getSelected(null,function(tab) {
currentPage = tab.url;
});
var page;
if (currentPage.toLowerCase().indexOf("item?id=") > -1) {
page = 'seller';
name(page, names[i]);
}
else if (currentPage.toLowerCase().indexOf("showpost.aspx?postid=") > -1) {
page = 'forum';
name(page, names[i]);
}
else if (currentPage.toLowerCase().indexOf("user.aspx?") > -1) {
page = 'profile'
name(page, names[i]);
}
}
});
chrome.tabs.getSelected executes asynchronously so the if statement was running before currentPage was set. Move the if statement inside the callback.
var names = ['hunter5deer', 'pielovingcat', '199MS', 'harrdy']
$(function() {
for (i=0;i<names.length;i++) {
chrome.tabs.getSelected(null,function(tab) {
var currentPage = tab.url;
var page;
if (currentPage.toLowerCase().indexOf("item?id=") > -1) {
page = 'seller';
name(page, names[i]);
}
else if (currentPage.toLowerCase().indexOf("showpost.aspx?postid=") > -1) {
page = 'forum';
name(page, names[i]);
}
else if (currentPage.toLowerCase().indexOf("user.aspx?") > -1) {
page = 'profile'
name(page, names[i]);
}
});
}
});

Detect anchor is leading to an active window.location

Having such an html:
<a class="someclass" href="some/url/absolute/or/relative">Blah</a>
... along with such javascript:
$("a.someclass").onclick(function() {
var link = $(this).attr("href");
if (link == window.location) // <<<<<<<<<<<<
doSomethingSpecial();
else
doOtherThing();
return false;
});
this code obviously doesn't work.
How to reliably detect that some anchor is leading to the current browser location?
Here are some notes:
Anchor's href could be either absolute or relative.
the fragments of the URLs should be ignored.
The problem is that $('a').attr('href') always returns the relative path. You need to use the native obj.href attribute to get the absolute path, strip hashes and then compare:
var clean = function(str) {
return str.replace(/(\#.*)/,'').toLowerCase();
}
$("a.someclass").click(function(e) {
if (clean(this.href) == clean(window.location)) {
// the link destination is equal to window.location (excluding hashes)
doSomethingSpecial();
} else {
doOtherThing();
}
e.preventDefault();
});
EDIT:
If you want to compare pathnames, you can grab it directly from the anchor element:
$("a.someclass").click(function(e) {
if (this.pathname == window.location.pathnname) {
doSomethingSpecial();
} else {
doOtherThing();
}
e.preventDefault();
});
AFAIK, you cannot detect that. Because I can write onclick event handler and then write the code that leads to the current location itself. In this case you can't really depend n the href attribute.
function ReloadWin()
{
window.location.reload();
}
Click me to reload
try this:
$(document).ready(function(){
$("a.someclass").click(function(){
//convert both to lower case
var h=$(this).attr("href").toLowerCase();
var l=window.location.href.toLowerCase();
//if has hash tag remove portion after if
if(l.indexOf("?")>0)
l=l.substring(0,l.indexOf("?"));
if(l.indexOf("#")>0)
l=l.substring(0,l.indexOf("#"));
if(l.length > h.length)
l = l.substring(l.length - h.length);
if(l==h){
alert("On same page");
}else{
alert("Other page");
}
return false;
});
});

Categories

Resources