How to trigger slideToggle(); when a visitor visits another page? - javascript

I have written a piece of code which triggers a slideToggle() after a 2 second wait on a page.
Now, this is not something I want to show to visitors who have the intention to immediately leave (bounce) from my site.
I determined that the best time to show the div is when a visitor has landed on my page, and navigated to another page.
So right now my code is this:
<script>
jQuery(document).ready(function(){
setTimeout(
function()
{
jQuery(".slide-div").slideToggle();
}, 2000);
});
</script>
Is there a way to listen to a visitor's behavior and trigger a function (slideToggle() in this case) when this visitor has navigated to another page?
This way, I can show my div to people who have navigated the website.

For future reference, I ended up using PHP to solve this problem.
Explanation: Each time a person navigates (or refreshes) the page, +1 is added to the $_SESSION['count'] variable. Then in footer.php I wrote a simple if else statement to determine wether my function should appear or not. wonderplugin is just a plug-in that checks if a visitor is on mobile or not.
Header.php:
<?php
session_start();
if (!isset($_SESSION['count']))
$_SESSION['count'] = 1;
else
$_SESSION['count']++;
?>
Footer.php:
<?php
$count = $_SESSION['count'];
if ($count == 1) {
//
}
elseif ($count >= 1 && $count <= 100) {
if (wonderplugin_is_device('iPhone,iPod,Android'))
echo get_function_mobile();
else
echo get_function();
}
?>

If you want a count of how many pages your users have been on you would need to hold onto a variable somewhere that is not on your page that you could increment with a page count. That may be in local storage, a cookie, or in your server side code.
Another thing you could do is add query strings to links on your pages if all you want to know is that someone has navigated from another page within your site. Then, check the query string on the page load and show your div if they are coming from an internal page.

You can use Javascript and localStorage to remember the user's action :
jQuery(document).ready(function()
{
var previousAction = localStorage.getItem('user-action');
if(previousAction)
{
setTimeout(function()
{
jQuery('.slide-div').slideToggle();
}, 2000);
}
else
{
localStorage.setItem('user-action', 'new-action-spotted');
}
});

Related

How to prevent a php page from browser back button?

I have a form which contains many drop-down and numeric slide-bar.
I am using post method to pass the selected variables to another page. Where I am getting the variables in the next page by $_POST() method.
And I am updating the variables passed into the database, after updation giving javascript pop-up as "you have saved successfully".
So my problem is when I click on browser back button, the values are getting updated in the database again and again. How can I prevent this by disabling browser back button.
You can have your post method open up a new tab so that there is no back navigation to go to:
<!DOCTYPE HTML>
<html>
<body>
<form action="www.google.com" method="post" target="_blank">
<input type="submit">
</form>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('#theSubmit').on('click', function () {
setTimeout(function(){
window.close();
}, 500);
})
</script>
The target generates the new window
And if you would like to close the old window add the two scripts that close the previous tab 500ms after the new tab is opened.
Instead of disabling the back button, you could redirect the user if he gets back to the page using sessions.
page1.php
session_start();
if (isset($_SESSION['block'])) {
header('Location: page2.php');
}
page2.php
session_start();
$_SESSION['block'] = true;
Another option:
This is how you could set values of all your input fields back, if the user clicks back:
page1.html
var block = localStorage.getItem("block");
window.addEventListener("beforeunload", function() {
if (block === 1) {
const block = true;
}
});
if (block) {
const inputs = document.getElementsByTagName('input');
for (input of inputs) {
input.value = '';
}
}
page2.html
localStorage.setItem("block", 1);
In this case, if you don't want your values get updated in your database, use:
if (!empty($_POST['my_value']) { // Add to database })
Don't disable the back button, fix the problem that the data is saved multiple times instead. You could use pass the users to a separate page with message "you have successfully...".
Then if the user tries to go back you look at $_SERVER['HTTP_REFERER'] if that is "successful.php" then don't save the data.
Disabling back buttons is a big reason for me to block a page so that I can't visit it again.
I truly hate when they do that or add several pages that you have to click back to get out of a page.
Whenever you post your data then you should check your post data that this is empty or not
<?php
if(isset($_POST) && !empty($_POST) ){
//your code for update
//Then after run update query and success message ,do empty the post
$_POST=array(); // empty the post
}
?>

php/js refresh variable without refresh page

i have problem with my php/js code.
I need to check every 1 second content of file, so before i'm going to load page i set adress.txt content to "localhost" then i go to my website and it displays me localhost, now i want to edit content of text file to "192.168.0.1", so i want to set automatically div text to new content without refresh, its still localhost not 192.168.0.1
My actual js:
$(document).ready(
function() {
setInterval(function() {
var randomnumber = Math.floor(Math.random() * 100);
$('#show').text("<?php echo file_get_contents("adress.txt");?>");
}, 1000);
});
How can i update div text to new txtfile content without refresh?
Sorry for bad english :)
PHP is a server-side language. Your <?php echo file_get_contents("adress.txt");?> executes only when the page is loaded (or refreshed). Then, if you want to do anything without refreshing, you need to use javascript. If you want to call some PHP code without refreshing, you can use AJAX. And you even don't need PHP if you just want to get content of some file.
Try this:
$(document).ready(function()
{
setInterval(function()
{
$.get('address.txt', function(data)
{
$('#show').text(data);
});
}, 1000);
});

JS onclick="history.go(-1) only if under my domain

I have a Joomla site, and I have the following problem, I need a "Back to search page" function on my product details page, and I am using this code after some changes according to replies to my initian question:
<br/><?php echo JText::_('VOLTAR'); ?>
Now, if a Visitor comes from another site directly to my product page and click this, he will be redirected to homepage of my site, and this is ok, but if I in a search page of my site, click on a product page and then click on the back to search link, the visitor is also redirected to my homepage, which is not good, it should be redirected to previous page, which was his own search page.
Is there any way to modify this code in order to accomplish something like:
if visitor comes from my search page or from anywhere in my site, by clicking this he will be redirected to the previous page, and if a visitor came from outside of my site, by clicking this he will be redirected to my homepage?
You can use document.referrer and compare it to window.location.host.
if (document.referrer.split('/')[2] === window.location.host)
if (document.referrer.indexOf(window.location.host) !== -1)
So your HTML will look like this:
<?php echo JText::_('VOLTAR'); ?>
Adding branching logic into an inline click handler gets messy. If you can move this to a function and reference it it will be far more readable.
if(document.referrer.indexOf('mysite.com') >= 0) {
history.go(-1);
}
else {
window.location.href = 'myHomePageUrl'; // this might just be '/' of your site
}
Edit:
If you are not concerned about adding names to the pages global scope you can create a function in a script tag immediately before the link you are creating:
<script>
function backClick() {
// above conditional goes here.
return false;
}
</script>
<br/><?php echo JText::_('VOLTAR'); ?>
I have tried some of the codes above and I needed to make some changes to make it work for me.
remove href=""
"window.location.href" must have
http://
function backClick() {
if (document.referrer.indexOf(window.location.host) !== -1) {
history.go(-1); return false;
}
else { window.location.href = 'https://stackoverflow.com'; }
}
<a onclick="backClick()">go back</a>

Conditional refreshing page - how to set a referrer?

I want to refresh my particular page, when referrer is blank.
To do this I used this script:
if (document.referrer === "" && document.URL.match("mysite.com/page1/module1")){
window.location.reload();
}
Of course it refreshes endlessly - because after refreshing the site the referrer is blank too.
How can make it to refresh only one time?
Try this:
top.location.href = top.location.href;
Instead of this:
window.location.reload();
And it's better to use PHP to make this condition:
<?php
if(!$_SERVER['HTTP_REFERER']) {
echo '<script>top.location.href = top.location.href;</script>';
}
?>
Anyway what you are trying to do is very bad practice, because many people are blocking browser to send referers.

AJAX keeping data on refresh

I currently have a like button that now works with Ajax. With one minor flaw. I click like on a post and it updates 1 like and shows in the page. But if I refresh the page it vanishes out of sight. The like is still in the database it just doesn't show in the page. Now someone told me to use
$(document).ready(function () {}
to do this on page load, but I have no clue how to use it to make my likes show on page refresh.
Or maybe I have to make a new call on page refresh to get all the likes for each post.
This is what I have so far
function likestatus(postid,contextid){
var obj = document.getElementById(contextid);
$.post("../include/like_do.php", { streamitem_id: postid},function(data){
//see the parameter data in this function. Data contains whatever that you echo in your php file.
$("#likesprint"+postid).html(data+"Likes");
});
}
Like_do.php
<?php
session_start();
require"load.php";
if(isset($_POST['streamitem_id'])){
$check = user_core::check_liked($_SESSION['id'],$_POST['streamitem_id'],1);
user_core::do_like($_SESSION['id'],$_POST['streamitem_id'],1);
echo $check; // as your user_core::check_liked() function returns number of likes.
}else{
echo "<script>alert('Error liking post');</script>";
}
?>

Categories