Open popup when specific link

Asked

Viewed 39 times

0

I have to open a popup on a specific page.

My JS is like this:

if($('.popup-banner').length > 0) {
    $('.popup-banner .fechar, .popup-banner .link-fechar, .popup-overlay').click(function() {
        $('.popup-overlay, .popup-banner').fadeOut(300);
    });
}

At the moment, it’s opening on any page I access. But, I only want to open when I’m at home, the home home home address is www.teste.com.br

  • 2

    Felipe, I think, if you want the behavior to only fire on the home page, you could use if (window.location.href === '/') on line two, before connecting the function click on the element.

2 answers

4


You can do so much with window.location.href and check the URL, for example:

if ( !!location.href.match("https?:\/\/pt.stackoverflow.com\/?$") ) {
    alert("Página inicial")
}

Or you can do with window.location.pathname and check the path of the URL, for example:

if ( !!window.location.pathname.match("(?:\/|index\.(?:php|asp|html?))$") ) {
    alert("Página inicial")
}

Explanation of Regex 1:

https?:\/\/pt.stackoverflow.com\/?$
   └┬┘                         └─┬─┘
    │                            └──── Informa que a URL tem que terminar com `/`. / ou /
    └───────────────────────────────── Informa que o `s` como opcional. Isso serve tanto para http://, quanto https://

Explanation of Regex 2:

(?:\/|index\.(?:php|asp|html?))$
 └┬┘ └───────────┬──────────┘
  │              │             
  │              │            
  │              └──────────────── ou terminar com index.php; index.asp; index.html; ou index.htm
  └─────────────────────────────── Informa que o `path` deve terminar com `/`

The !! serves to convert the result to boolean.

If you want something much simpler, you can use slice, for example:

if (location.pathname.slice(-1) === "/") {
    alert("Página Inicial");
}

2

One way is to take the variable location.href (Current URL) and remove www., http://, https:// and bar /. If the result is just teste.com.br, you are on the home page:

var url_ = "http://www.teste.com.br/"; // apenas para teste. Apague esta linha
//var url_ = location.href; // descomente esta linha
url_ = url_.replace(/www.|https|http|:|\//g,"");

if($('.popup-banner').length > 0 && url_ == "teste.com.br") {
   
   $("div").show(); // apenas para exemplo. Apague esta linha
   
    $('.popup-banner .fechar, .popup-banner .link-fechar, .popup-overlay').click(function() {
        $('.popup-overlay, .popup-banner').fadeOut(300);
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="popup-banner" style="display: none;">popup página inicial</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.