Javascript mobile redirect script - javascript

I'm working a wordpress website that needs a mobile redirect to the mobile home page in case the user is using a cell. I'm trying to utilize this Javascript code but I'm having major difficulties getting it to work properly.
I need help removing the conformation section that asks the user if they want to continue to mobile site.
I also need help figuring out how to restructure the code so it doesn't keep forwarding mobile user to home page. For example, I load the page on mobile, the code runs and it forwards me to mobile page. From there I click on another link in the top navigation and it takes me back to the home page no matter what I do.
Keep in mind I am very new to this so any Input and Help from you experienced folks out there would be much appreciated.
Thank You
P.
<script type="text/javascript">
if (screen.width < 1081) {
var ref = document.referrer;
var urls = new Array("http://www.mymainsite.com","http://m.mymobilesite.com");
var n = ref.match(urls[0]);
var m = ref.match(urls[1]);
if ((m!==null) || (n!==null)) {
stop;
}
else if (ref=='') {
var r = confirm("Small Display is Detected.\nClick \"OK\" for MOBILE SITE.");
if (r==true) {
window.location = "http://m.mymobilesite.com";
}
else {
stop ;
}
}
else
{
window.location = "http://m.mymobilesite.com";
}
}
</script>

We only activate this code on your main site. Then we check whether or not your screen width is small enough and look into localStorage to see whether or not the user has made a decision before. Then we put up the confirmation box. If the user clicks okay, we go to the mobile site, if not we set the localStorage variable to true. Keep in mind that localStorage is only available IE8+
if(location.hostname === 'mymainsite'){
if (screen.width < 1081 && !localStorage.isMainSite) {
if(confirm('Small Display is Detected.\nClick \"OK\" for MOBILE SITE.')){
window.location = "http://m.mymobilesite.com";
} else {
localStorage.isMainSite = true;
}
}
}

Related

How do I exclude something from an "if" statement in javascript?

I am using the same ip address for many websites, so they all share the same index. So, I made all requests redirect to the main domain, as long as its not the main domain. This works just fine. My problem, is that now I made a mobile version of my website. Now, every time someone goes to the mobile website, it redirects them forever, from the main page, to the mobile one.
Here's what I have so far:
var loc = window.location.href + '';
if (loc.indexOf('https://maindomain.com') - false); {
window.location.replace("https://maindomain.com")
}
language = "JavaScript" >
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
window.location.replace("https://mobilewebsite.com")
}

Mobile URL Redirect and Desktop URL Redirect

I need help please? I want to make my website that has a desktop and a mobile version. The CSS coding of styling to the correct widths of HTML elements are easy but a URL is harder.
I want to know is that how to make a URL that leads to a home page on desktop but on mobile the URL is different but it goes to the same home page as the desktop version but in the mobile version.
Do you know if there is any code that can do that with out getting any errors on previewing it privately. I don't mind if your answers are using PHP or JavaScript etc.
This is a code that i tried to use. I wasn't sure if it worked or not. Can't say it possibly did.
$(document).ready(function() {
$(window).on("load resize", function() {
if($(window).width() <= 950) {
var mobile = window.location = "/mindex.php";
console.log("The location is " + mobile);
} else if($(window).width() > 950) {
var desktop = window.location = "/index.php";
console.log("The location is " + desktop);
} else {
var defaultPlace = "";
console.log("Defualt location: " + defaultPlace);
}
});
});
Can you please help me? Remember, I would like some help on making a mobile redirect URL and a desktop URL but that will both lead to the same page but in different versions please.
You can use user-agent header sent by the browser to check whether the user is mobile user or desktop user and redirect according to the returned value. You can check user-agent header using this -
var usrAgent = navigator.userAgent;
Now you know the user agent, check the returned user-agent is mobile or not and redirect accordingly -
function detectMobile()
{
if(usrAgent.match(/Mobile/i))
{
return "Mobile";
}
}
var isMobile = detectMobile();
if(isMobile)
{
window.location = "MOBILE_URL";
}
else
{
window.location = "DESKTOP_URL";
}
Alternatively,
You can use html link tag to redirect to any webpage according to user device width using this -
<link rel="alternate" media="only screen and (max-width: 640px*)" href="MOBILE_URL_TO_REDIRECT">
*Change this width according to your requirement. 640px is the ideal max width for mobile devices.
I hope this solves your problem.

How do I disable a Sharepoint Web Part without being on the exact page?

Alright, so in my SharePoint (2013) site, I made a simple JavaScript Web Part to refresh the page every five minutes. I went to adjust the time, backspaced out where I'd entered the time to wait before a refresh, and without thinking exited the edit page. This left me in an infinite loop of refresh, and since I do not have admin access to the laptop I am working on, I cannot manually disable JavaScript. My hope now is to find a way to edit, or just delete, the Web Part causing this from elsewhere. Can this be done?
Here's the code I used:
<script type="text/javascript" language="javascript">
var reloadTimer = null;
var sURL = unescape(window.location.pathname);
function setReloadTime(secs)
{ if (arguments.length == 1)
{ if (reloadTimer) clearTimeout(reloadTimer);
reloadTimer = setTimeout("setReloadTime()", Math.ceil(parseFloat (secs)*1000));
}
else
{ reloadTimer = null;
location.reload(true);
window.location.replace( sURL );
}
}
setReloadTime(); //Here was where I had 300
</script>
You can add parameter Contents=1 to URL of the webpart page. It displays page in setup mode allowing you to remove webpart from the page. The final URL will look like this http://portal.contoso.com/page.aspx?Contents=1

How can I detect exit intent on a mobile browser?

I'm working on a solution to detect exit intent on safari mobile. (or any mobile browser for that matter)
On desktop I can track curser movement and when the user breaks the plane of the webpage I can initiate a pop up. See http://www.quicksprout.com/about/ as an example. Move your curser up to the back button on the browser and as soon as your curser breaks the webpage a pop up will appear. How can I solve this in a mobile environment?
Is there any way to detect when someone clicks the Safari address bar and before the favorites screen appears I can launch a pop up then?
Thank you in advance for the help.
I know this is over a year later, but maybe my answer might still help someone in the future.
On some of my sites, I found that mobile exit intent often consists of a slight upward scroll before the user hits their back button. For example, users often scroll down the page quite a bit while consuming content, but when they're ready to leave they might scroll upwards slightly (say 5-10% of the page height), and then they'll go hit the back button or close the tab.
I use that knowledge to pop up a newsletter sign up form on some of my content sites, and it actually works well without annoying the user. So if I ever detect that a user scrolled down at least 50% of my page, then back up by at least 5%, I hit them with a popup since I think they liked my content but are ready to exit the page. I wrote some simple Javascript that actually lets me detect such behavior at https://github.com/shahzam/DialogTriggerJS
Not sure if that's the exact answer you're looking for, but hope that helps a bit!
I just came back from a long trip around the web with the same goal in mind however as of now - you really are not able to detect if a user clicks on the address.
However I found out that you can look for patterns that users are making before they are ready to leave your website or abandon shopping cart. Here is show how we solved this and made mobile exit intent work on all mobile devices in case if the user quickly scrolls back up the page since that can be a sign that shows that the user has lost interest in our content and might want to leave.
Detecting if the user is on a mobile device.
This part is rather simple - we use Javascript to check if the event is "touchstart" and if so, we are adding a class to our body tag:
jQuery(document).on('touchstart', function(){
$(body).addClass('on-mobile-device');
});
Detecting the scroll direction, scroll speed and displaying Exit Intent popup:
function myScrollSpeedFunction(){
if( jQuery('body').hasClass('on-mobile-device') ){
if(my_scroll() < -200){
//Your code here to display Exit Intent popup
console.log('Must show mobile Exit Intent popup')
}
}
}
var my_scroll = (function(){ //Function that checks the speed of scrolling
var last_position, new_position, timer, delta, delay = 50;
function clear() {
last_position = null;
delta = 0;
}
clear();
return function(){
new_position = window.scrollY;
if ( last_position != null ){
delta = new_position - last_position;
}
last_position = new_position;
clearTimeout(timer);
timer = setTimeout(clear, delay);
return delta;
};
})();
jQuery(document).on('scroll', myScrollSpeedFunction );
This is basically it. This way you are not interrupting the user's flow since the user has already finished looking at the content and going up very quickly and we can present him with a message.
What we have done ourselves besides this code is to make sure our Exit Intent popup is displayed only in case if the user has got a product in his shopping cart since we are suggesting to save the users shopping cart and remind about his abandoned cart via email.
You can test it out on our product page here: https://www.cartbounty.com, just remember to add a product to the shopping cart before you test drive it on your mobile device.
At least on mobile safari, you're looking for the window.onpagehide function. This event will fire immediately after the page is hidden.
Here is a snippet showing this code in action:
<!DOCTYPE html>
<html>
<head>
<script> window.onpagehide = function(e) { alert("Don't go! I'm lonely!"); }</script>
</head>
<body>
</body>
</html>
Unfortunately, it looks like if you want an event to fire before the page is hidden, you're out of luck, because mobile Safari halts execution of everything on the page when the user clicks on the address bar. This means that you cannot, for example, monitor the page height to see if the user is typing on the keyboard (as they would be if they clicked the address bar).
Some simple code to detect exit intent on a mobile device.
It detects exit intent through the speed of the user's upwards scroll.
It delays 10 seconds before enabling. You probably should make it about 30 seconds if you only want to show your exit intent popup to people who are really interested in your content.
setTimeout(() => {
document.addEventListener("scroll", scrollSpeed);
}, 10000);
scrollSpeed = () => {
lastPosition = window.scrollY;
setTimeout(() => {
newPosition = window.scrollY;
}, 100);
currentSpeed = newPosition - lastPosition;
console.log(currentSpeed);
if (currentSpeed > 160) {
console.log("Exit intent popup triggered");
document.removeEventListener("scroll", scrollSpeed);
}
};

Cancel Redirect in Javascript?

i added this to the head of my page:
<script type="text/javascript">
if (screen.width <= 800) {
window.location = "http://m.domain.com";
}
</script>
i have a button on my mobile version called "Main Site".
I want the button to go to my main site, but not redirect back to my mobile site. How do i do this?
also, i only want them to go there once. So, the next time they enter my website name, i want it to take them to mobile site
If you already have a button to go your main site. Just link the main site to that button. What you can do extra is, use an url parameter to check and force the main layout. Something like
Main site
Check for this parameter, when you want to force the main layout. Or else, the script currently using will automatically do what you want to do.
Use the following function to read the query string. [Source]
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
Next you can use it in your logic, like this:
if (screen.width <= 800 && getParameterByName('forceLayout') != 'main') {
window.location = "http://m.domain.com";
}
You could inspect document.referrer
<script type="text/javascript">
if (screen.width <= 800 && document.referrer.indexOf('http://m.domain.com') != 0) {
window.location = "http://m.domain.com";
}
</script>
When someone clicks on your "Main site" button, before you redirect to your main site, create a "MobilOptOut" cookie and then test for the presence of that cookie in your screen.width if statement.
The client needs to manage the state of the current view the user wants to see. Since HTTP is a stateless protocol, you can use a cookie to persist the user's selection across HTTP requests.
When the user clicks the button to display the main version, delete the cookie as part of the click event. Likewise, set the cookie to your desired value when the user wants to view the mobile version. Since there are many ways to manipulate cookies with JavaScript that may be library dependent, below is pseudocode of what your page should do.
// Pseudocode:
// Sets a cookie named "view" with the value "mobile"
function setMobileView() {
Cookie.set("view", "mobile");
}
mobileViewButton.onclick = setMobileView;
// Deletes the cookie named "view"
function setMainView() {
Cookie.delete("view");
}
mainViewButton.onclick = setMainView;
Here is pseudocode for what your redirection logic would look like:
// Pseudocode for deciding the view to display
if (view === "mobile") {
location.href = "http://m.domain.com";
}

Categories