What does the question mark mean in this function? - javascript

Here's the documentation for this plugin (There's only two functions.)
http://tkyk.github.com/jquery-history-plugin/#documentation
$(document).ready(function() {
function load(num) {
$('#content').load(num +".html");
}
$.history.init(function(url) {
load(url == "" ? "1" : url);
});
$('#ajax-links a').live('click', function(e) {
var url = $(this).attr('href');
url = url.replace(/^.*#/, '');
$.history.load(url);
return false;
});
});
Here's the html:
<body>
<h1>jQuery History Plugin Ajax Sample</h1>
<div id="ajax-links">
<ul>
<li>load 1.html</li>
<li>load 2.html</li>
<li>load 3.html</li>
</ul>
<div id="content"></div>
<hr />
</div>
<p>[All samples] [Project home]</p>
</body>

load(url == "" ? "1" : url);
The question mark here is a a ternary if operation, Simply put, it is a short, inline if statement.
Expanded out, the statement would look something like this:
if (url == "")
load("1");
else
load(url);
If the statement before the question mark evaluates to true, then the left-hand side of the colon is used, otherwise (if it is false) the right-hand side is used. You can also nest this, though it isn't always a good idea (for readability).

Its shorthand for:
If (url == ""){
load("1");
}
else {
load(url);
}
Ie. If url equals "" then return "1", otherwise, return url
In your example, if the url equals "" then, 1.html will be loaded, otherwise, url + ".html" will be loaded

It is a ternary operation.

Related

How to redirect user on another page depending on location using JS/JQuery?

I am trying to write a simple script to redirect users on different pages depending on their location.
Basically, the https://ipapi.co/country/ page is returning a value based on locations, such as "GB" - for the UK. So when the script returns "GB", the user should be redirected to UK.html.
You can notice that in the second condition, I am trying to use an array of countries. If the user is from IT or FR or DE, then I want him redirected to EU.html.
Because I'm a complete beginner, I think something is missing in the following code and I hope you can help me understand what is missing and what would be the correct code to write.
<script type="text/javascript">
$.get('https://ipapi.co/country/', function(country){
console.log(country)
})
if (country = "GB") {
window.location.replace("UK.html");
}
else if (country = ["FR","IT","DE","CH"]) {
window.location.replace("EU.html");
}
else {
window.location.replace("US.html");
}
</script>
Thank you!
change window.location.replace("US.html") to window.location="US.html"
<script type="text/javascript">
$.get('https://ipapi.co/country/', function(country){
console.log(country)
})
if (country === "GB") {
window.location="UK.html";
}
else if (["FR","IT","DE","CH"].indexOf(country )!==-1) {
window.location="EU.html";
}
else {
window.location="US.html";
}
</script>
I will provide a simple solution which does not require jQuery.
One function will make a request to https://ipapi.co/country/.
A second function will perform the redirect depending on the response of the first.
<script type="text/javascript">
const whatCountry = function(){
const xhr = new XMLHttpRequest()
xhr.open("GET", "https://ipapi.co/country/")
xhr.onload = function(){
checkCountryAndRedirect(xhr.response)
}
xhr.send()
}
const checkCountryAndRedirect = function(country){
if(country === "GB"){
window.location.replace("UK.html");
} else if(country === "FR" || country === "IT" || country === "DE" || country === "CH"){
window.location.replace("EU.html")
} else {
window.location.replace("US.html")
}
}
</script>
Once these two functions are defined, you can call the request with whatCountry()
To clarify, the part of your code that checks for country must be part of the callback, as AJAX requests are asynchronous.
The if checks you are doing will always evaluate to true, because a single = indicates that you are assigning the value on the right to country.
The second if statement would be checking whether country was the array ["FR","IT","DE","CH"]. To check whether country was one of those four countries, you can test whether country is equal to each of those countries (not a very clean solution). You can also use switch statements, but I like the indexOf solution suggested above.
EDIT: I have used window.location.replace but window.location = ... would be more suited to your case.

Make javascript if statement display html?

I wanted an if statement to show an image or html code depending on the webpage. I got this far and the html table doesn't appear at all (appears blank):
<script type="text/javascript">
<!--
var url = document.location.pathname;
if( document.location.pathname == '/tagged/photos' ){
document.innerHTML('<table><tr> hello </tr> </table>');
}
if( document.location.pathname == '/tagged/news' ){
document.write("<b>This is my news page</b>");
}
//-->
</script>
I'd do it slightly differently
Add both markup to the page, and show/hide as approproate:
<table id="table"><tr> hello </tr></table>
<span id="title"><b>This is my news page</b></span>
<script type="text/javascript">
$(function(){
var url = document.location.pathname;
if( url == '/tagged/photos' ){
$('#title').hide();
$('#table').show();
}
if( url == '/tagged/news' )
{
$('#title').show();
$('#table').hide();
}
})
</script>
I have assumed you have JQuery since it is tagged
You're using document.innerHTML, which doesn't exist. At the very least, you need to get a proper element:
document.documentElement.innerHTML = 'some HTML';
Setting aside everything else that's wrong with this approach, I'm not sure, why would you use document.write() in one branch and someElement.innerHTML in the other.
I'd suggest the following approach:
function pagePopulate() {
// you're looking at the pathname, use a sensible (meaningful) variable-name:
var pagePath = document.location.pathname,
// this is a map, of the relationship between page and content:
pathToContent = {
// pagename : html
'photos': '<table><tbody><tr><td>photos page</td></tr></tbody></table>',
'news': '<b>This is the news page</b>'
},
// getting a reference to the <body> element:
body = document.querySelector('body');
// setting the innerHTML of the <body>,
// if pagePath = 'tagged/photos', splitting with '/' would return:
// ['tagged','photos'], calling 'pop()' returns the last element of the array
// 'photos', which returns that string to the square brackets, resulting in:
// pathToContent['photos'], which would yield the '<table>...</table>' HTML.
// if that call resulted in an undefined, or falsey, value, then the default
// (the string *after* the '||' would be used instead:
body.innerHTML = pathToContent[pagePath.split('/').pop()] || '<h2>Something went wrong</h2><img src="http://blog.stackoverflow.com/wp-content/uploads/error-lolcat-problemz.jpg" />';
}
// calling the function:
pagePopulate();
References:
|| (logical 'or' operator).
Array.prototype.pop().
document.querySelector().
String.prototype.split().

If document URL indexOf

I have some search page link: www.example.com/search.php?search=search_word, I am tried to make a default search URL. If people only type www.example.com/search.php via the browser, make a default URL as www.example.com/search.php?search=aaa. My code does not work.
<script src="../jquery.js"></script>
<script>
jQuery(document).ready(function(){
var currneturl = document.URL;
if(!document.URL.indexOf('?')){
document.URL = currneturl + '?search=aaa';
}
});
</script>
The .indexOf() method returns -1 if the string is not found, and -1 is a truthy value such that !-1 is false. You need to explicitly test for -1:
if (document.URL.indexOf('?') === -1) {

Why doesn't my if-else statement work?

Can anyone see why this does not work:
<script>
if (url==showbasket.html||order1.html||order2.html||order3.html||order4.html) {
document.write('<span style="font-family:lucida;font-size:10px;">Hello</span>');
} else {
document.write('<span style="font-family:lucida;font-size:30px;">Hello Hello</span>');
}
</script>
I´m trying to write a script that do this:
IF URL = 1.html or 2.html or 3.html or 4.html THEN
write option1
ELSE
write option2 (for all other URL´s)
if (url == "showbasket.html" || url == "order1.html" || url == "order2.html" || url == "order3.html" || url == "order4.html")
You have to do the check for each url and if it's a string use quotes
I don't think you got your if condition right:
if (url == showbasket.html || url == order1.html || ...
This code is valid, but it will not do what you want
if (url==showbasket.html||order1.html
"url==showbasket.html" checks if "url" is equal to the "html" attribute of object "showbasket". Since showbasket does not exist, your code will throw an exception.
"||order1.html" means the same, check if the "html" attribute of "order1" object is "true"
Like others have said, what you want to do is :
if ( url == "showbasket.html" || url == "order1.html"

If Statement not working with And (&&) Operator

I'm having a hard time writing up what seems should be a simple if statement! I need it to say if mod does not equal a, b, or c - then do this. Here is what I was trying but have been unsuccessful:
var mod = CURRENT_MODULE_ID;
if (mod != "5827289" && mod != "5195103" && mod != "5181422") {
doSomething();
}
When I type this into my editor it says there is an error, specifically that "The entity name must immediately follow the '&' in the entity reference."
.. and is not working when I go to test.
Any help is appreciated!!
UPDATE:
The url: esber.squarespace.com
The full script:
<script type="text/javascript" src="/storage/scripts/sessvars.js"></script>
<script type="text/javascript">
<![CDATA[
onload=function(){
sessvars.browserConfirmation?'none':'';
sessvars.ageConfirmation?'none':'';
};
var mod = Squarespace.Constants.CURRENT_MODULE_ID;
if (mod != "5827289" && mod != "5195103" && mod != "5181422") {
if(sessvars.ageConfirmation != "yes"){
window.location = "/verify/";
};
};
]]>
</script>
I want every page in the site to automatically redirect on page load to the verify page, unless it is the verify page (/verify), the "You are not verified" page (/not-verified), or the login page (/login) -- unless the user already verified by setting the sessvars, then they can continue on to the homepage.
To test this I go to esber.squarespace.com and click on one the menu items at the right (this menu would eventually be hidden when I'm done with the page) -- when i try to go to another page without veriying my age first i should be redirected back to the /verify page but that isnt happening.
If i revise the script to:
<script type="text/javascript" src="/storage/scripts/sessvars.js"></script>
<script type="text/javascript">
onload=function(){
sessvars.browserConfirmation?'none':'';
sessvars.ageConfirmation?'none':'';
};
var mod = Squarespace.Constants.CURRENT_MODULE_ID;
if (mod != "5827289") {
if(sessvars.ageConfirmation != "yes"){
window.location = "/verify/";
};
};
</script>
then it works fine(?)
Try this:
// <![CDATA[
onload=function(){
sessvars.browserConfirmation?'none':'';
sessvars.ageConfirmation?'none':'';
};
var mod = Squarespace.Constants.CURRENT_MODULE_ID;
if (mod != "5827289" && mod != "5195103" && mod != "5181422") {
if(sessvars.ageConfirmation != "yes"){
window.location = "/verify/";
};
};
// ]]>
If this doesn't work, just leave the code there for a bit, so that we can debug it directly on your website
Wrap your script in a CDATA section.
<script type="text/javascript">
<![CDATA[
// script here
]]>
</script>
I tried the EXACT same code as yours and it works fine:
function doSomething() {alert("doing");}
var CURRENT_MODULE_ID = 5195103000;
var mod = CURRENT_MODULE_ID;
if (mod != "5827289" && mod != "5195103" && mod != "5181422") {
doSomething();
}
It did 'doSomething'. When value is changed to 5195103, nothing happens which is correct
The editor aside, what's the script error when you run it and what's the browser you used? I suspect it could be an error elsewhere or perhaps related to CURRENT_MODULE_ID ?
Are you embedding this javascript in an xml document?
It sounds like the xml document is not well formed, perhaps because the & should be escaped as &
The javascript by itself looks fine too me
Try:
var mod = CURRENT_MODULE_ID;
if (mod != "5827289" && mod != "5195103" && mod != "5181422") {
doSomething();
}
You'll find out that way whether the javasciprt needs to be escaped
Edit in response to comment:
Try the following:
<script type="text/javascript">
<![CDATA[
var mod = CURRENT_MODULE_ID;
if (mod != "5827289" && mod != "5195103" && mod != "5181422") {
doSomething();
}
]]>
</script>
It sounds like your editor just thinks you're working with an XML document. Have you tried actually running this in a browser? If so, does the browser also give an error?
Are you trying to compare the ID as a string or value? Did you try it without quotes?
var mod = CURRENT_MODULE_ID;
if (mod != 5827289 && mod != 5195103 && mod != 5181422) {
doSomething();
}
or another method would be to use match
var mod = CURRENT_MODULE_ID;
if (!mod.match("5827289|5195103|5181422")) {
doSomething();
}
I got this error within a script section in an XSL file.
Entity '&' not defined
I adapted the above answer within my script and it worked.
Note the CDATA section in the code segment below
<script>
var Quantity860=<xsl:value-of select="$QuantityOrdered_860" />;
var Quantity850=<xsl:value-of select="$QuantityOrdered_850" />;
var QuantityToReceive860=<xsl:value-of select="$QuantityLeftToReceive_860" />;
if(parseFloat(Quantity860.textContent) !== parseFloat(Quantity850.textContent) <![CDATA[ && ]]> parseFloat(QuantityToReceive860.textContent) !== parseFloat(Quantity850.textContent))
{
Quantity860.style.color="#FF6347";
Quantity850.style.color="#FF6347";
QuantityToReceive860.style.color="#FF6347";
}
</script>
just use != in comparison instead of == then && will work
if(val != "" && val != "") {
console.log("filled");
}else
{console.log("empty"); }

Categories