Link to a modal window from URL - javascript

Title says it all, I would like to trigger a jQuery event that opens a unique model window depending on which URL is used. I've looked at a few solutions and all of them seem to require bootstrap which I am not using or simply don't seem to work for me.
I think i understand the logic, I'm just not sure how to actually code it and would be grateful for some help. Here is my thinking:
[STEP 1]
On page load, check the URL.
If the the url is normal e.g. "www.domain.com/example", don't do anything.
If the url has a substring on the end e.g. "www.domain.com/example/#red", "www.domain.com/example/#green", or "www.domain.com/example/#blue" etc., set that substring to a variable. In this case the variable would equal either red, green, or blue.
[STEP 2]
Insert the variable where the line of code says [color] and execute.
$("document").ready(function() {
$(".details, #[color]details").trigger('click');
});

use with window.location.hash. its will get the hash value form url with# .so no need to add # in the dom
$("document").ready(function() {
if(window.location.hash.trim().match(/(\w+)/)){
$(".details,"+window.location.hash+"details").trigger('click');
}
});

You can use document.referrer to get the Page URL.
Store it in a variable to fetch the last segment or the URL using substr().
Then check it in conditional operator if the last part is your desired text, add it to your class and trigger.
I ll paste my code which I used on the next page to trigger tab change for some requirement. I hope this will work for you too, hopefully. Thank you.
$(document).ready(function () {
var referrer = document.referrer; // Get the Url of the previous page
var lastPathSegment = referrer.substr(referrer.lastIndexOf('/') + 1); // extracts the last part e.g. the page name
if(lastPathSegment == "invoices.php"){
customer_detail_content();
$('a[href="#tab_6_2"]').trigger('click');
}

Related

Hash URL on pageload in jQuery

I really hope to find a solution here.
Need to load specific elements highlighted first on the pages based on url hash.
I have already set up "click" and "hover" functions for these elements. But also need these elements highlighted based on url. What selector should I use?
Basically I need the following scenario to be implemented:
if https://mypage.com#case1 loads
do this
if https://mypage.com#case2 loads
do this
If I understand your question, you can get the URL and do a simple if else statement where you load what you need to based on the URL string.
It could be something like this:
var url = window.location.href; //get url string
if(url == "https://mypage.com#case1"){
//run your case1 code
}else if(url == "https://mypage.com#case2"){
//run your case2 code
}
I'm not sure what your use case is, but you probably want to parse the URL to get the relevant piece or parameter you are looking for.

Javascript window.location returning two different values?

I am using a JS popup window for an Oauth2 Implicit Grant. I'm using JS to monitor for URL changes to get the code grant.
newWindow.addEventListener('unload', function(e)
{
console.log(e.currentTarget.location);
if (e.currentTarget.location.href.includes('code='))
{
var url = new URL(e.currentTarget.location.href);
alert(url.searchParams.get('code'));
}
});
The problem I am having is that the location field is giving two different values for the href parameter.
As you can see in the image, the href parameter has two different values. How do I make sure I always get the second value?
The Location is evaluated some time before.
If you hover over the little blue i icon, it says:
Value below was evaluated just now.

Need help rewriting a url with JavaScript/Jquery

I have a userscript (http://userscripts.org/scripts/show/179402) that I'm writing that adds a bar to Google Sites like the one they removed. I'm needing the script to take the value of the search field and add it to a url (Replacement URL) and have it replace the url (Original URL) on the bar. In other words, I need to update it where the search term carries over to other pages, like the original google bar they removed.
I've tried this a few different ways. One way I tried was getting the value this way. Which, gets the value fine.
$('#gbqfq').keyup(function() {
var searchterm = this.value;
});
Then I've tried to add the search term to a url that replaces the original URL this way
var url1search = "https://www.google.com/search?q="+searchterm;
$('#url1').attr("href", url1search);
How do you replace a url with a new url plus a variable?
I'm very new to JavaScript, I'm making this script to try to learn it. If someone can help me figure out how to do this I would appreciate it very much.
Ah sorry, I see your problem. searchterm is only defined inside the anonymous function, it would be undefined elsewhere. Try moving rest of the script inside that function too.

window.location.href strange behavior

Here is my problem:
window.location.href = "(X(1)S(" + "#Session.SessionID" + "))/Cart/AddToCart?productID=" + "#Model.ProductID";
Basically on click of <p> tag I want to call this link with sessionID in the url. The problem is it either doubles the sessionID part or it adds the whole string at the end of current url. When I remove this part "(X(1)S(" + "#Session.SessionID" + ")) everything works fine. Any ideas why it's doing that?
Solution:
I have no idea why did I get two negative votes, but the issue was, I needed a '/' before the session ID. That's it!
Depending on how your session handler is passed, it may get appended automatically to any URL, so that you don't have to do it yourself. Since you're doing it yourself anyway, it gets doubled up by the automatic one.
Because you set window.location.href to an inappropriate value. It should be set to a proper URI, which usually don't look like (X(!)S(... but start with http://...

Why does my if condition prevent either clause from executing?

I'm trying to re-write the URLs of a set of links that I select using a jQuery class selector. However, I only wish to re-write the links that don't already have a href attribute specified, so I put in an if/else construct to check for this... However, it's not working. It does work without the if else statement so I'm pretty sure that is where I screwed up. I'm new to both JavaScript and jQuery so sorry if my question is elementary and/or overly obvious.
var url = window.location;
var barTwitter = $("a.shareTwitter").attr('href');
if (barTwitter).val() == "null") {
$("a.barTwitter").attr('href','http://www.twitter.com/home?status='+ url +'');
} else {
$("a.barTwitter").attr('href',barTwitter);
}
if (barTwitter).val() == "null") {
This is syntactically invalid (count the parentheses!). You rather want to do:
if (barTwitter.val() == "null") {
Further, the val() function only works on input elements which are wrapped by jQuery, not on element attribute values which are at end just normal variables. You rather want to compare normal variables against the literal null:
if (barTwitter == null) {
There are actually a few problems with your code... BalusC correctly describes the first one - syntax errors in your if condition - but you should probably consider some of the rest...
I'll start with your code corrected according to BalusC's answer, with comments added to describe what's happening:
var url = window.location; // obtain the URL of the current document
// select the href attribute of the first <a> element with a shareTwitter class
var barTwitter = $("a.shareTwitter").attr('href');
if (barTwitter == null) { // if that attribute was not specified,
// set the attribute of every matching element to a combination of a fixed URL
// and the window location
$("a.barTwitter").attr('href','http://www.twitter.com/home?status='+ url +'');
} else {
// set the attribute of every matching element to that of the first
// matching element
$("a.barTwitter").attr('href',barTwitter);
}
Other issues with your code
Ok... now the problems:
jQuery matches sets - a single selector can potentially match multiple elements. So if there are multiple links on the page with the shareTwitter class, you'll be pulling the href attribute for the first one, but changing all of them. That's probably not what you want, although if there is only a single link with that class then you don't care.
In the else clause, you're not actually modifying the href at all... Unless you have multiple matching links, in which case you'll change all of them such that they have the href of the first one. Again, probably not what you want, although irrelevant if there is only one link... So, in the best-case scenario, the else clause is pointless and could be omitted.
You can actually omit the if/else construct entirely: jQuery allows you to test for the existence of attributes in the selector itself!
You're including the URL of the current page in the querystring of your new, custom URL - however, you're not properly escaping that URL... This could cause problems, as full URLs generally contain characters that are not strictly valid as part of URL querystrings.
Notes on working with JavaScript
A quick aside: if you plan on doing any development using JavaScript, you should obtain some tools. At minimum, install Firebug and familiarize yourself with the use of that and JSLint. The former will inform you of errors when the browser fails to parse or execute your code (in addition to many, many other useful debugging and development tasks), and the latter will check your code for syntax and common style errors: in this case, both tools would have quickly informed you of the initial problems with your code. Instructing you in the proper use of these tools is beyond the scope of this answer, but trust me - you owe it to yourself to take at least a few hours to read up on and play with them.
Toward safer code
Ok, back to the task at hand... Here's how I would re-write your code:
var url = window.location; // obtain the URL of the current document
// escape URL for use in a querystring
url = encodeURIComponent(url);
// select all <a> elements with a shareTwitter class and no href attribute
var twitterLinks = $("a.shareTwitter:not([href])");
// update each selected link with a new, custom link
twitterLinks.attr('href', 'http://www.twitter.com/home?status='+ url +'');
Note that even though this new code accomplishes the same task, it does so while avoiding several potential problems and remaining concise. This is the beauty of jQuery...
firs of all your syntax is screwed up: if (barTwitter).val() == "null") should be if (barTwitter.val() == "null") or if ((barTwitter).val() == "null")
Secondly barTwitter is either going to be a string or null so you cant call val which is a jQuery Object method specific to input elements.
Lastly you probably dont want to compare to null because it possible the value will be an empty string. Thus its better to use length property or some other method. A sample with lenght is below.. but im not sure what attr returns if if ther eis no value... check the docs.
var url = window.location;
var barTwitter = $("a.shareTwitter").attr('href');
if (barTwitter.length < 1) {
$("a.barTwitter").attr('href','http://www.twitter.com/home?status='+ url +'');
} else {
$("a.barTwitter").attr('href',barTwitter);
}

Categories