Limiting Popup to load on homepage- Shopify - javascript

I want this script to load only on homepage, at the moment it is opening in all the pages on my Shopify store. I am using QuickShop Theme. Below is the code, this code is for my newsletter popup. Any help would be appreciated. Thanks a ton in advance.
<script type="text/javascript">
jQuery(document).ready(function($){
var $_form = $('#mc-form');
var $_action = $_form.attr('action');
$_form.ajaxChimp({
url: $_action,
callback: function(resp){
//
}
});
});
$(window).load(function() {
{% if settings.popup_expires == '0' %}
$.removeCookie('popup_cookie');
{% endif %}
var $_popup_cookie = $.cookie('popup_cookie');
if ($_popup_cookie == undefined){
setTimeout(function(){
$('#mc-form-fancybox').fancybox({
'beforeClose': function(){
if($("#mc-popup-hide").is(':checked')){
$.cookie('popup_cookie', 'yes', { expires: {{settings.popup_expires}} });
}
else{
// no set cookie
}
}
}).trigger('click');
}, 1000);
}
});
</script>

Instead of putting your script in theme.liquid, try putting it in index.liquid instead. theme.liquid is rendered for every page on your site, but index.liquid is your homepage template.

There are many possible ways to do this. You could only include the script on your home page, that way it would only fire on the page its getting loaded on. If you can't do this you can always interrogate the window.location property to work out what page you are.
Try putting window.location into the JavaScript console of your browser and see what comes back. You'll get properties such as host (e.g. stackoverflow.com), href (e.g. Limiting Pop to load on homepage- Shopify), pathname (e.g /questions/23427460/limiting-pop-to-load-on-homepage-shopify) and more.
Using this you can work out if you are on the homepage or not and not fire your fancybox.
There are many other possibilities as well, that's just off the top of my head. I would recommend just making sure it is included in just your home page if you can, but if not the window.location property may help.

Related

Avoid requesting the same external script twice

I request an external script by adding this to my HTML file:
<script>
$(document).on("turbolinks:load", function() {
$.getScript("https://example.com/script");
});
</script>
Say the content of the script is as follows:
doSomething = function() {
// ...
};
My website is a Ruby on Rails app with Turbolinks, which caches the content of the requested script between page visits. My script tag does not know about this, so if I revisit the page it will request the script again. How do I avoid this? My current solution is to check if the scripts content is known:
<script>
$(document).on("turbolinks:load", function() {
if (!window.doSomething) {
$.getScript("https://example.com/script");
}
});
</script>
But this depends on the content inside the script staying the same. So I would rather check if a script from the source https://example.com/script already exists? Or maybe some other approach. Any ideas?
Like epascarello commented, $.getScript appends to head so check that it's not in head before getting it.
if (!$('head script[src^="https://example.com/script"]').length){
$.getScript("https://example.com/script");
}
Use the Attribute Starts With Selector because $.getScript appends a timestamp to avoid getting an already cached version, i.e. it requests a new URL each time.
If you're going to use it more than once:
function getScriptOnce(url){
let selector = 'head script[src^="' + url + '"]';
if (!$(selector).length){
$.getScript(url);
}
}
getScriptOnce("https://example.com/script");

Need Condition for This Script To Redirect The Page if #wrapper is hide

JavaScrpt expert,
i want if the below script exist in my template coding then my page should redirect to example.com
<script>
$(document).ready(function(){
$("#wrapper").hide();
})
</script>
if the above script exist in my template, then it should redirect to example.com
Attention: please add some condition in that script like this:
<script>
$(document).ready(function(){
If
//#wrapper is hide
$("#wrapper").hide();
//then it should redirected to example.com
</script>
I hope someone will figure out and will share code with me. thanks.
If you need this functionality somewhere after the bit of code you show, this would work:
var $wrapper=$("#wrapper");
if($wrapper.length>0 && !$wrapper.is(':visible')){
// #wrapper exists on the page but is not visible, redirect user
window.location.href = "http://example.com";
}
What Taplar says is:
<script>
$(document).ready(function(){
// $("#wrapper").hide();
window.location.href = "http://example.com";
})
</script>
If you need this behaviour in another place in your code, then see DelightedD0D answer.
Very good point by DelightedD0D, I've fixed the code. ;)
DelightedD0D, I'd give you another point if I could.

Execute Javascript on new HTML-Page

I have two HTML-Pages (A.html and B.html). On Page A there is a button called "UploadButton"
<input id="UploadButton" type="button" value="Dateien auswählen" />
This is connected to some jQuery code
<script language="javascript" type="text/javascript">
$(function () {
$().SPServices({
operation: "GetList",
listName: "Doc",
async: false,
completefunc: function (xData, Status) {
id = $(xData.responseXML).find("List").attr("ID");
}
});
reference = "./_layouts/Upload.aspx?List=" + id + "&RootFolder=";
$('#UploadButton').click(function (event) {
NewItem2(event, reference);
return false;
});
});
</script>
So far so good... The Button or a little closer the NewItem2() method open up a new HTML Page (Page B). On page B there is an anchor I want to click.
So my question is, how can I click an anchor on page B with a Script from page A. Is there a possibility to do that? I don´t know how to do that properly.
The NewItem2() is not written through my hands, so I cant tell you whats happening in there. I tried to find something via Google or in the forum but I don´t know how to call my problem so I found nothing, sorry.
Thankls for all effort!
Simple - You cant´t use Page A`s scriptvariables on Page B.
When you just want to click an HTML anchor, why don´t you simply add #anchorname to your reference to create the same effect?
The easiest way to submit information between pages is the QueryString.
Just pass the ID of the control which you want to click and write some javascript to read the QueryString and execute the .click().
Should use external JavaScript file by copying your JavaScript/jQuery code to the onther file and set extencion .js in last include your this this file in both page (A.html and B.html) as shown below.
<SCRIPT TYPE="text/javascript" SRC="|YOUR FILE NAME|" />
So you does not need to specify different methods for different pages where same type of action are being done.
If window.open is used to open that new window, than you can take a refference to that window like this:
var newWindow = window.open("...new window url here...");
and than, using newWindow you can access its content:
newWindow.$("#anchore_to_click").click()
(assuming jquery is available there too)

Change URL AND CSS when an element is clicked

Basically, I have several pages on my website where I am using PHP to include the content in the page, and using jQuery to "switch" between the content by setting the display in CSS to "none" or "block". However, I am struggling to get it to work in the main page with the menu. So I need when the user clicks on the appropriate link, the page will change to the page where the content is contained, but also apply the appropriate CSS as to display the appropriate content. So far I have (URL blocked out):
<script type="text/javascript">
$(document).ready(function(){
$('#ourMissionMenu').click(function() {
window.location = 'http://beta.***.com/aboutUs.php';
$('#rightReplace').css({
"display":"none"
});
$('#ourHistory').css({
"display":"none"
});
$('#meetTeam').css({
"display":"none"
});
$('#communityOutreach').css({
"display":"none"
});
$('#connectUs').css({
"display":"none"
});
$('#blog').css({
"display":"none"
});
$('#ourMission').css({
"display":"block"
});
});
});
</script>
If you change the location of the window, all javascript from the current page will cease. You cannot expect javascript from one page to control content on another page. This would be a massive security violation.
You need the javascript to run on "aboutUs.php", or dynamically load the aboutUs content into your current page. Or, better still, have aboutUs.php have the correct css in the first place.
Can't aboutUs.php just link to a CSS file that has the correct styles? Why do they need to be set in Javascript?
It also looks like the css() calls will be applied to the current page, and not the target page.
Once you change the window.location property, the browser will redirect the user to the specified URL and the execution of JavaScript will stop immediately.
So your .css() function calls are not being run but that doesn't matter much because they would be altering the DOM on the current page, not the next page.
Those .css() function calls need to be run on the next page, something like this:
First Page --
$(function(){
$('#ourMissionMenu').click(function() {
window.location = 'http://beta.***.com/aboutUs.php';
});
});
Second Page (aboutUs.php) --
$(function(){
$('#rightReplace').css({
display:"none"
});
$('#ourHistory').css({
display:"none"
});
$('#meetTeam').css({
display:"none"
});
$('#communityOutreach').css({
display:"none"
});
$('#connectUs').css({
display:"none"
});
$('#blog').css({
display:"none"
});
$('#ourMission').css({
display:"block"
});
});
But this would be pretty strange if you are dynamically building the aboutUs.php page. You might as well leverage your use of PHP and set the display of the element with PHP instead of JavaScript (which is client-side, meaning it requires the user's browser to do work).
On top of what Paul and Sérgio mentioned, you can concoct the selectors like below rather than multiple blocks.
$('#rightReplace,#ourHistory,#meetTeam,#communityOutreach,#connectUs,#blog,#ourMission').hide();

Reload an HTML page just once using JavaScript

How can I reload an HTML base web page only once? I am using history.go(0); with function onLoad in body tag but i want to run it only once. Please keep in mind that I am using iframe so this is not possible to to use the below types code:
<script language=" JavaScript" ><!--
function MyReload()
{
window.location.reload();
}
//--></script>
<Body onLoad=" MyReload()" >
The above code did not work for me.
However the code below is working well but the problem is that I need it to load only once:
<BODY BGCOLOR=#FFFFFF background="../images/Index_04.jpg" onLoad="history.go(0)" >
Note: I am using two iframes when user click on main page link a page loads in iframe then I want to reload the whole page with current iframe page.
You could use a querystring at the end of the page url (e.g. ?r), and check for it before redirecting, as if it exists, the redirect is already done.
if(window.location.href.substr(-2) !== "?r") {
window.location = window.location.href + "?r";
}
Disclaimer: I agree with others that you probably have a better solution - and should never need to refresh 'just once'.
Explanation of use
At the bottom of your page, just above the </body> you should put this:-
<script type="text/javascript">
if(window.location.href.substr(-2) !== "?r") {
window.location = window.location.href + "?r";
}
</script>
That's it.
<script type="text/javascript">
$(document).ready(function(){
//Check if the current URL contains '#'
if(document.URL.indexOf("#")==-1)
{
// Set the URL to whatever it was plus "#".
url = document.URL+"#";
location = "#";
//Reload the page
location.reload(true);
}
});
</script>
Due to the if condition the page will reload only once. Hope this will help.
Here is another solution which works for me using localStorage. In this solution we don't need to modify existing url.
<script type='text/javascript'>
(function()
{
if( window.localStorage ){
if(!localStorage.getItem('firstReLoad')){
localStorage['firstReLoad'] = true;
window.location.reload();
} else {
localStorage.removeItem('firstReLoad');
}
}
})();
</script>
The only way I can think of to do this is by using cookies (or if your on the right platform, sessions) and flag the first time it has reloaded, variables might also work in this case, because we're speaking about IFRAME, but I have never tried such thing.

Categories