I use the window.onload function throughout my website, via a single external .js file, and I usually check to see what page i'm on, so that certain statements will run, e.g:
window.onload = function() {
var curPage = document.getElementById('page').value;
if (curPage === "index.html") {
// do something here
}
if (curPage === "about.html") {
// do something else here
}
}
with 'curPage' being a value from an input within each html document
<input id="page" type="hidden" value="my-page.html" />
I see people adding an id to the body element to achieve the same effect, like so:
<body id="pageisIndex">
However, I would like to know if there is an even better way to initialize/pull a variable within the HTML document without the use of an input or element id.
would something like ...
<script type="text/javascript">
var curPage === 'index.html';
</script>
... be alright/proper to use while also using an external .js file?
EDIT:
All of the answers provided are very good, I believe this is one of those times where it comes down to an individuals opinion; however, using location.pathname or document.URL are great methods that I will be testing out. Awesome!
EDIT 2:
I found something pretty cool I thought I would post here, the following gives us the last page within the path.
page = location.pathname.split('/').pop();
console.log(page);
You could possibly try RegExp with given page name itself without any hidden field:
var url = window.location.pathname;
if(url.match('index.html')) {
//to do
} else if(url.match('about.html')) {
//to do
} else {
//to do
}
You can use:
location.pathname
which returns everything in the url after the domain. For example, for this page it's:
/questions/27956897/window-onload-to-determine-what-code-to-run-depending-on-page-value
It does not include the query string if present.
If you want just what follows the last forward-slash, that's discussed in this post: Get value of a string after a slash in JavaScript, which will work if you don't care about the rest of the path but just want to extract the filename.
I used the last option you have shown which seemed to be a good solution. Setting a variable at the beginning of a page and checking its value is easy. I think instead of giving the exact page name I would go for something which is meaningful like "intropage" or "sellingpage" which will be easier to decipher at a later time.
<script type="text/javascript">
var curPage = 'intropage';
</script>
Another approach that could be to used if you don't want to set id or variable is to check the location.pathname or location.href to get the current location and take necessary steps.
Related
I'm a student learning JavaScript. I don't know how to do this, but I imagine there has to be a way to.
I'm looking to reference a script throughout my website so that any time a specific URL is reached (which can be accessed through most pages within the site) the script redirects the page to a different URL just after the original URL is loaded.
I'm imagining something like this,though I know this doesn't work:
function urlRedirect (onload = "window.location.href= 'url1.com'")
{
window.location.replace = 'url2.com'
};
I'd also be interested if this possible outside of JavaScript if anyone can think of how to do this. Thanks.
Make sure you read basic JavaScript Syntax first.
I guess that the function you want:
function urlRedirect() {
if (window.location.href == 'url1.com') {
window.location = 'www.url2.com';
}
}
I would assign the function to the window onLoad event.
window.onload = function(){
if (window.location.href == 'http://url1.com'){
window.location.replace('http://url2.com');
}
}
Haven't tested the code but something like that should work.
I have a method that is set dynamically to different textboxes in my form. But the problem is that i only want the method to work if i am on my view called riskscore.cshtml. It there a way? like a if(page == riskscore.cshtml){ do method} kind of code?
JavaScript typically has no way of knowing if or when a particular view file was used server-side. It only knows the results that the view rendered.
You can wrap the contents of the view in say a <div class="riskscore">, then select textboxes within those:
$('.riskscore :text')...
You also mentioned in a comment that other elements won't exist without this view. You can use them as your condition, checking whether they exist:
if ($('.other-elements').length) {
// do method
}
Replace '.other-elements' as needed.
You can test URLs in JavaScript:
if(/\/riskscore\.chtml$/.test(window.location.pathname)) {
// You're on riskscore.chtml... Do something
}
you can use window.location to get the current location. or you can use location.pathname to current path.
link here
I think it will help
Here is my question, I am using jsp script, trying to match a key word in requesting url and do something:
<script>
$url = '${pageContext.request.requestURL}';
if("${fn:contains(url, 'key')}" == true){
...
}
....
But this doest work... I am not sure where the problem is but I want it to be like when url contains this string, go in to the if condition.
Thank you
You are mixing JSP/EL and JavaScript as if they run in sync. This is wrong. JSP/EL runs in webserver and produces HTML code which get executed in webbrowser. JavaScript (JS) is part of the generated HTML code and runs in webbrowser only.
You need to do it either fully in JSP/EL, or fully in JavaScript. You can use JSP/EL to dynamically generate JS code which get later executed when the page arrives at browser. Rightclick page in browser, do View Source to see what JSP/EL has generated. You should not see any line of JSP/EL. You should only see HTML/JS code. It's exactly that JS code which get executed then.
You're using a JSP EL function to test a JS variable which isn't in the variable scope at that moment at all. This is not going to work. It can only test JSP/EL variables.
Here's how you could do it in pure JS:
<script>
var url = window.location.href;
if (url.indexOf('key') > -1) {
// ...
}
</script>
If you really insist in doing it using JSP/EL, you could do as follows:
<script>
var url = '${pageContext.request.requestURI}';
if (${fn:contains(pageContext.request.requestURI, 'key')}) {
// ...
}
</script>
This will then generate the following JS code (rightclick page in browser and View Source to see it):
<script>
var url = '/some/uri';
if (true) {
// ...
}
</script>
But this makes no sense. Whatever functional requirement you need to solve, you need to think twice about the right approach. Feel free to ask a new question about solving the concrete functional requirement the proper way.
If you want a parameter that the page was requested with, use ${param.paramName}. So in this case ${param.key}. See implicit objects in the docs. And if you just want to check it has a value try ${not empty param.key}.
Using a Java-based back-end (i.e., servlets and JSP), if I need the contextPath from JavaScript, what is the recommended pattern for doing that, any why? I can think of a few possibilities. Am I missing any?
1. Burn a SCRIPT tag into the page that sets it in some JavaScript variable
<script>var ctx = "<%=request.getContextPath()%>"</script>
This is accurate, but requires script execution when loading the page.
2. Set the contextPath in some hidden DOM element
<span id="ctx" style="display:none;"><%=request.getContextPath()%></span>
This is accurate, and doesn't require any script execution when loading the page. But you do need a DOM query when need to access the contextPath. The result of the DOM query can be cached if you care that much about performance.
3. Try to figure it out within JavaScript by examining document.URL or the BASE tag
function() {
var base = document.getElementsByTagName('base')[0];
if (base && base.href && (base.href.length > 0)) {
base = base.href;
} else {
base = document.URL;
}
return base.substr(0,
base.indexOf("/", base.indexOf("/", base.indexOf("//") + 2) + 1));
};
This doesn't require any script execution when loading the page, and you can also cache the result if necessary. But this only works if you know your context path is a single directory -- as opposed to the root directory (/) or the multiple directories down (/mypath/iscomplicated/).
Which way I'm leaning
I'm favoring the hidden DOM element, because it doesn't require JavaScript code execution at the load of the page. Only when I need the contextPath, will I need to execute anything (in this case, run a DOM query).
Based on the discussion in the comments (particularly from BalusC), it's probably not worth doing anything more complicated than this:
<script>var ctx = "${pageContext.request.contextPath}"</script>
Got it :D
function getContextPath() {
return window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
}
alert(getContextPath());
Important note: Does only work for the "root" context path. Does not work with "subfolders", or if context path has a slash ("/") in it.
I think you can achieve what you are looking for by combining number 1 with calling a function like in number 3.
You don't want to execute scripts on page load and prefer to call a function later on? Fine, just create a function that returns the value you would have set in a variable:
function getContextPath() {
return "<%=request.getContextPath()%>";
}
It's a function so it wont be executed until you actually call it, but it returns the value directly, without a need to do DOM traversals or tinkering with URLs.
At this point I agree with #BalusC to use EL:
function getContextPath() {
return "${pageContext.request.contextPath}";
}
or depending on the version of JSP fallback to JSTL:
function getContextPath() {
return "<c:out value="${pageContext.request.contextPath}" />";
}
Reviewer the solution by this
Checking the solution of this page, make the following solution I hope it works:
Example:
Javascript:
var context = window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
var url =window.location.protocol+"//"+ window.location.host +context+"/bla/bla";
I render context path to attribute of link tag with id="contextPahtHolder" and then obtain it in JS code. For example:
<html>
<head>
<link id="contextPathHolder" data-contextPath="${pageContext.request.contextPath}"/>
<body>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
main.js
var CONTEXT_PATH = $('#contextPathHolder').attr('data-contextPath');
$.get(CONTEXT_PATH + '/action_url', function() {});
If context path is empty (like in embedded servlet container istance), it will be empty string. Otherwise it contains contextPath string
A Spring Boot with Thymeleaf solution could look like:
Lets say my context-path is /app/
In Thymeleaf you can get it via:
<script th:inline="javascript">
/*<![CDATA[*/
let contextPath = /*[[#{/}]]*/
/*]]>*/
</script>
I'm trying to get to learn som javascript/jQuery stuff, and I'm really struggling with this one. It's basically a question of structure – how to do things in the best possible way.
I've got this function that randomly picks out a list item from one of three unordered lists (where all list items have been hidden), and shows it. Depending on what page I'm currently on, I would like to select a list item from one list in particular. All my lists are "marked" with an id, to make them unique.
I could pass an argument to my randomize function with the list id of my choice, to make it only select an item from that particular list. However, this would mean that I would have to place inline scripts in the html (one script tag with custom function call for each page), and from what I've heard inline scripts tehnd to block page rendering. And that would be bad, becuase I care about performance. Another way could be to have lots of if/else clauses, such as "if body has class the_classname -> randomize from the list with with id the_id". That would however mean that the script would have to make lots of unnecessary queries on the DOM.
Don't know if there's a term for what I'm talking about. Perhaps something like "conditional function calls" or maybe "page based function calls".
How would you tackle such a problem? I know my CSS & HTML, but am quite new to javascripting. Just trying to do the right thing...
One way would be to create a javascript file that you include in the header of all your pages. The javascript file will contain your function that takes a pageId, and returns a list item based on the page
function getListItem(pageId) {
switch (pageId) {
...
}
}
Assign an ID attribute to the BODY tag of each page, corresponding to the pageId in your javascript function:
<body id="home-page">
Then, on your page load, you can pass in the ID value to your function using jQuery:
<script type="text/javascript">
$(function() {
var listItem = getListItem($('body').attr["ID"]);
} );
</script>
This would pass in "home-page" to your javascript function and return the list item determined by the logic inside your javascript function.
The very best way to do this would be to examine the url (no DOM traversal involved, no additional external scripts, so it's fast):
var path = window.location.pathname;
if (path.indexOf('/a_unique_url') !== -1) {
// do code for the page 'a_unique_url';
} else if (path.indexOf('/another_unique_url') !== -1) {
// do code for the page 'another_unique_url';
} else {
// do default action, because none of the above were found.
}
A little more wordy on your part, but faster if you have a lot of unique operations would be to use a switch statement and the full path, like this:
var path = window.location.pathname;
switch(path) {
case '/full/path/after/domain.html':
// do code for the page '/full/path/after/domain.html';
break;
case '/some/other/path.html':
// do code for the page '/some/other/path.html';
break;
case '/yet/another/path.html':
// do code for the page '/yet/another/path.html';
break;
default:
// do default action, because none of the above were found.
break;
}
Although, if you have access to server side scripting, there are more efficient methods for these kind of operations.
To circumvent the possibility of your scripts holding up the browser it's common practice to place your scripts just before the end of your body tag.
You may even want to look into asynchronous script loading.
Friend, I don't understand exactly what you want, but I'll try to help:
the inline javascript will block your page if you put them alone in the middle of your code, but you can say to them to execute only when the page was loaded with this code:
window.onload = function (){
//call your function with the desired parameter
}
So when your page loads, the function on window.onload will be executed.
Add it from the server-side at run-time: Page.RegisterClientScriptBlock Method
Customize it with a property from the code-behind;
function myFunction() {
var theParameter = '<%# parameterName>';
// do something
}