Three .indexOf not match - return another result - javascript

I have a redirect based on the OS in mobile devices.
I try to return the redirect in the following script
$(document).ready(function (){
//Android Version:
if(navigator.userAgent.toLowerCase().indexOf("android") != -1) {
window.location.href = "https://link1";
}
if(navigator.userAgent.toLowerCase().indexOf("iphone") != -1){
window.location.href = 'https://link2';
}
if(navigator.userAgent.toLowerCase().indexOf("ipad") != -1){
window.location.href = 'https://link3';
}
});
I need fourth redirect if none of the above true. But when I use at the end of the script:
else {
window.location.href = 'https://link4';
}
Only ipad redirect works. Iphone and android redirects to link4.

Each of the if statements needs an else if after it so that instead of 3 separate if statements, with the last one having an else, you have one if statement with multiple conditions.
$(document).ready(function (){
//Android Version:
if(navigator.userAgent.toLowerCase().indexOf("android") != -1) {
window.location.href = "https://link1";
} else if(navigator.userAgent.toLowerCase().indexOf("iphone") != -1){
window.location.href = 'https://link2';
} else if(navigator.userAgent.toLowerCase().indexOf("ipad") != -1){
window.location.href = 'https://link3';
} else {
window.location.href = 'https://link4';
}
});

You need else on all of your subsequent ifs. So:
$(document).ready(function (){
//Android Version:
if(navigator.userAgent.toLowerCase().indexOf("android") != -1) {
window.location.href = "https://link1";
} else if(navigator.userAgent.toLowerCase().indexOf("iphone") != -1){
// ---^^^^
window.location.href = 'https://link2';
} else if(navigator.userAgent.toLowerCase().indexOf("ipad") != -1){
// ---^^^^
window.location.href = 'https://link3';
} else {
window.location.href = 'https://link4';
}
});
That way, if the first if's condition is true, you only do what's in the if block. If the first if's condition is false, you do the next if, and only do what's in its if block if it's true. If none of theifconditions is true, you end up doing theelse` block at the end.
The above is the standard way to write it, but this verbose way may help make it clearer:
$(document).ready(function (){
//Android Version:
if(navigator.userAgent.toLowerCase().indexOf("android") != -1) {
window.location.href = "https://link1";
} else {
if(navigator.userAgent.toLowerCase().indexOf("iphone") != -1){
window.location.href = 'https://link2';
} else {
if(navigator.userAgent.toLowerCase().indexOf("ipad") != -1){
window.location.href = 'https://link3';
} else {
window.location.href = 'https://link4';
}
}
}
});
That does exactly the same thing my first code block above does.

Related

How to break if/else statement in JavaScript once a condition is true

So I have this basic JavaScript code to detect a user language and redirect to the proper page based on the browser language, the issue I am facing is that the if/else statement keeps going as an infinite loop and the browser keeps refreshing.
The code is set on a separate file and is included only in the en-US page, the code is a stand-alone, not using any function.
if(userLang == "en-US"){
window.location.href = "domainame.com/faq.html";
}
else if(userLang == "nl"){
window.location.href = "domainame.com/faq-de.html";
}
else if(userLang == "fr"){
window.location.href = "domainame.com/faq-fr.html";
}
else if(userLang == "es-ES"){
window.location.href = "domainame.com/faq-es.html";
}
else if(userLang == "ja"){
window.location.href = "domainame/faq-ja.html";
}
I expect the browser to check for the user language and redirect to the proper page, instead, the browser keeps refreshing.
You can add an extra check to only change the page if it is not the current page.
Something like this:
let lanPage = '';
if(userLang == "en-US"){
lanPage = "https://domainame.com/faq.html";
} else if(userLang == "nl"){
lanPage = "https://domainame.com/faq-de.html";
} else if(userLang == "fr"){
lanPage = "https://domainame.com/faq-fr.html";
} else if(userLang == "es-ES"){
lanPage = "https://domainame.com/faq-es.html";
} else if(userLang == "ja"){
lanPage = "https://domainame/faq-ja.html";
}
if(lanPage && lanPage !== location.href) {
location.href = lanPage;
}

Different redirects in function of multiple referer

Now I have this code of redirect in function of the referer:
document.addEventListener('DOMContentLoaded', function() {
console.log(isMobile);
var referrer = document.referrer;
if(referrer.indexOf('site1.com') !== -1 || referrer.indexOf('site2.com') !== -1) {
if(isMobile.phone) {
window.location = "http://www.landingphone.com";
console.log('Is phone');
} else if(isMobile.tablet) {
window.location = "http://www.landingtablet.com";
console.log('Is tablet');
} else {
window.location = "http://www.landingdesktop.com";
console.log('Is desktop');
}
} else {
window.location = "http://www.anotherlanding.com";
}
});
Its ok this code for redirect in function of the referer site1 and site2.com, but if I need redirect also another referer (for example site3.com) to another landing (for example www.landingphone2.com, landingtablet2.com and landingdesktop2.com). What I need add in the code? what i need modify?
Thank you very much.
You can try something like this, adding another else if statement as referred to in the comment to your answer.
document.addEventListener('DOMContentLoaded', function() {
console.log(isMobile);
var referrer = document.referrer;
if (referrer.indexOf('site1.com') !== -1 || referrer.indexOf('site2.com') !== -1) {
if (isMobile.phone) {
window.location = "http://www.landingphone.com";
console.log('Is phone');
} else if (isMobile.tablet) {
window.location = "http://www.landingtablet.com";
console.log('Is tablet');
} else {
window.location = "http://www.landingdesktop.com";
console.log('Is desktop');
}
} else if (referrer.indexOf('site3.com') !== -1) {
// Do your other redirects here
} else {
window.location = "http://www.anotherlanding.com";
}
});

jQuery click to run a function, click again to run another

I'm trying to run a small piece of jQuery - when it's clicked it runs a function and when clicked again it runs another.
I have tried the following but this doesn't even run the first.
$('body').on('click', '.card--small', function() {
console.log('clicked');
$(this).addClass('card--expanded');
if (topCheck() == 'chrome') {
$('.card--expanded .card--small__container').css({
'top': '51px'
});
}
}, function() {
console.log('clicked again');
$(this).removeClass('card--expanded');
if (topCheck() == 'chrome') {
$('.card--expanded .card--small__container').css({
'top': '0'
});
}
});
function topCheck() {
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf('safari') != -1) {
if (ua.indexOf('chrome') > -1) {
console.log('Chrome');
} else {
return 'safari';
console.log('Safari');
}
}
}
Just use the card--expanded class as a flag to determine which click you need and design your function accordingly.
$('body').on('click', '.card--small', function (e) {
var self = $(this),
isExpanded = self.hasClass('card--expanded'),
isChrome = topCheck() === 'chrome'; // will always be false as topCheck never returns 'chrome' (it returns either 'safari' or undefined).
self.toggleClass('card--expanded', !isExpanded);
if (!isExpanded) {
console.log('clicked');
if (isChrome) { // will never execute as isChrome will always be false
$('.card--expanded .card--small__container').css({
'top': '51px'
});
}
} else {
console.log('clicked again');
if (isChrome) { // will never execute as isChrome will always be false
$('.card--expanded .card--small__container').css({
'top': '0'
});
}
}
});
The point is to use some external condition as a flag to keep track of the click state. This could be a global variable, or a local variable above your handler in the scope chain (or a CSS class, or a HTML5 data attribute, etc.). There are a number of ways to do this. Using a CSS class seems like a natural fit in your case.
Also, the topCheck function would be better written if there were a chance it could return 'chrome':
function topCheck() {
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf('safari') > -1) {
if (ua.indexOf('chrome') > -1) {
return 'chrome';
console.log('Chrome');
} else {
return 'safari';
console.log('Safari');
}
}
}
or
function topCheck() {
var ua = navigator.userAgent.toLowerCase(),
browser = 'unknown';
if (ua.indexOf('safari') > -1) {
if (ua.indexOf('chrome') > -1) {
browser = 'chrome';
console.log('Chrome');
} else {
browser = 'safari';
console.log('Safari');
}
}
return browser;
}
Personally, I dislike multiple return statements per function so I would use the second form.
$('.card--small').click( function(){
// run function 1
function_1();
$(this).unbind('click').click( function(){
// run function 2
function_2();
});
});
Inside function 2 you would have to rebind $('.card--small') to run function 1 on click, if you want to run function 1 again.
A simple approach without jQuery. Just keep some kind of state around to determine what to do.
<html>
<head>
<style>
div {
background-color: #ff0;
}
</style>
<script>
var state = 0;
function runIt() {
if (state > 0) {
doSomethingDifferent();
state = 0;
return;
}
doSomething();
state = 1;
}
function doSomething() {
alert("something");
}
function doSomethingDifferent() {
alert("something different");
}
</script>
</head>
<body>
<div onClick="runIt()">Click me</div>
</body>
</html>
Another approach would be to rebind the click event to another function.
In your function topCheck nothing is returned when you detect Chrome. You only log it. Your click event calls the function topCheck but does not get anything back from the function when Chrome is detected. So your if statement probably gets an undefined value.
To answer your original question on how to toggle function called on click, your code should look something like this:
function click1() {
// ...
$(this).off('click', click1).on('click', click2)
}
function click2() {
// ...
$(this).off('click', click2).on('click', click1)
}
$('#link').on('click', click1)
Live demo
But from your code snippet it seems that it would be simpler to implement toggling in single function:
$('body').on('click', '.card--small', function() {
if (!$(this).hasClass('card--expanded') {
$(this).addClass('card--expanded');
if (topCheck() == 'chrome') {
$('.card--expanded .card--small__container').css({
'top': '51px'
});
}
} else {
$(this).removeClass('card--expanded');
if (topCheck() == 'chrome') {
$('.card--expanded .card--small__container').css({
'top': '0'
});
}
}
});
Try
css
.card--small__container {
top:0px;
display:block;
position:relative;
}
js
$("body")
.on("click", ".card--small", function () {
if (topCheck() == "Chrome"
&& !$(this).data("clicked")
&& !$(this).hasClass("card--expanded")) {
$(this).data("clicked", true)
.addClass("card--expanded")
.css("top", "51px");
} else if ( !! $(this).data("clicked")
&& $(this).hasClass("card--expanded")) {
$(".card--small")
.css("top", "0")
.removeClass("card--expanded");
}
});
function topCheck() {
var ua = navigator.userAgent.toLowerCase();
return ua.indexOf("chrome") !== -1 ? "Chrome" : "Safari"
};
http://jsfiddle.net/o4ebav8t/

jquery form validation without click -> when ok show div

is it possible to do this automatically. mean when i type text and click on the second textfield autocheck the first one. then when both ok show the div2 and so on.
here is some code
var step1 = function() {
var first = $("#f_name").val();
var last = $("#l_name").val();
var error = false;
if (first == "") {
$("#f_name").next().text("*ErrorMsg");
error = true;
} else {
$("#f_name").next().text("");
}
if (last == "") {
$("#l_name").next().text("*ErrorMsg");
error = true;
} else {
$("#l_name").next().text("");
}
if (error == false) {
$("#send").submit();
$('#div1').show('slow');
} else {
returnfalse;
}
}
var step2 = function() {
var email1 = $("#e_mail").val();
var adress1 = $("#adress").val();
var error2 = false;
if (email1 == "") {
$("#e_mail").next().text("*ErrorMsg");
error2 = true;
} else {
$("#e_mail").next().text("");
}
if (adress1 == "") {
$("#adress").next().text("*ErrorMsg");
error2 = true;
} else {
$("#adress").next().text("");
}
if (error2 == false) {
$("#send2").submit();
$('#div2').show('slow');
} else {
returnfalse;
}
}
$(document).ready(function() {
$('#div1').hide();
$('#div2').hide();
$("#send").click(step1);
$("#send2").click(step2);
});
hope anyone can help me. and sorry for my bad english :)
greatings
The way that I would do it is:
Assign a variable, something like numSteps and set its initial value to 1
onFocus and onBlur, run a function that steps through each field, based on numSteps
If any fields are empty (or however you want to validate them), set error = true
if !error numSteps++
Make all elements up to numSteps visible
Hope this helps
Very crude example, but demonstrates what I was referring to:
http://jsfiddle.net/aSRaN/

Place a variable as a HREF

Basically, is it possible to do something like....
Click me!
<script>
function clicked() {
if(myVar == 1) {
link="http://stackoverflow.com"
}
else if (myVar == 2) {
link="http://google.com"
}
}
</script>
This example is probably impossible due to it firing at the same time...
But is it at all possible to use variables there?
Basically, I need a link that'll bring you to two different places depending on a variable.
I suppose I could have two links, and just hide/show each one respectively depending on the variable, but I was wondering if it's possible another way?
I'm working with HTML, CSS, JavaScript, and JQuery...
Thank you!
You could do...
$('a').click(function(event) {
if (condition) {
event.preventDefault();
window.location = 'http://different-url.com';
}
});
If the condition is met, then it will take you to a different URL.
Otherwise, the link will work as expected.
If you didn't want to use jQuery, that'd be...
var anchors = document.getElementsByTagName('a');
for (var i = 0, anchorsLength; i < anchorsLength; i++) {
anchors[i].onclick = function(event) {
if (condition) {
event.preventDefault();
window.location = 'http://different-url.com';
}
}
}
You could simply use Javascript to do a redirect:
<script>
function clicked() {
if(myVar == 1) {
window.location = "http://url1.com";
}
else if (myVar == 2) {
window.location = "http://url2.com";
}
}
</script>
No it's not possible to do it the way you want.
Why don't you do this instead -
Click me!
<script>
function clicked()
{
if(myVar == 1)
{
window.location.href = "www.stackoverflow.com";
}
else if (myVar == 2)
{
window.location.href = "www.google.com";
}
}
Take a look at Mozilla Developer Center for further references about the window.location object.
you could do this:
<script> function clicked() {
if(myVar == 1) {
window.location="http://stackoverflow.com"
}
else if (myVar == 2) {
window.location="http://google.com"
} }
</script>
Try this out
Click me!
<script>
function clicked() {
if(myVar == 1) {
location.replace("http://stackoverflow.com");
}
else if (myVar == 2) {
location.replace("http://google.com");
}
}
</script>
Cheers. This will take you to the desired place based on the myVar values!
function clicked() {
var dest = "";
if(myVar)
dest = "http://stackoverflow.com";
else
dest = "http://google.com"
window.navigate(dest);
But I see everyone said about the same. Just check which of the methods works on most browsers

Categories

Resources