I don't think this is a very basic question, but I need some help or if you can guide me to a resource I'd appreciate it. I have a script that I would like to run only when the visitor comes for the first time.
<script>
$(document).ready(function(){
$(".posts").hide();
$("#header").hide();
$("#body").hide();
$("#footer").hide();
$("#intro").click(function(){
$(".posts").show(3000);
$("#header").show(3000);
$("#body").fadeIn(3000);
$("#footer").show(3000);
$("#intro").hide();
$("p").hide();
});
});
How do I go about this? The visitor enters my site and everything is hidden, then they press a button and it shows everything in a cool way. I do not want to run this script again after visitor returns back to home page from some other page on the website. Any ideas on how this can be done? I am using javascript with jquery.
Thanks in advance.
UPDATE: Thank you Emeeus and Chiran K. for helping me. This is the code and it works fine. For first time visitor, we enter if-block, first time visitor clicks button and enters site. When visitor goes back to home page, it goes to else block, and hides what I want.
$(document).ready(function(){
if(!localStorage.getItem("firstTime")){
$(".posts").hide();
$("#header").hide();
$("#body").hide();
$("#footer").hide();
$("#start").click(function(){$(".posts").show(3000); $("#header").show(3000); $("#body").fadeIn(3000); $("#footer").show(3000);$("#start").hide(); $("p").hide(); });
localStorage.setItem("firstTime","true");
} else {
$("#start").hide();
$("p").hide();
}
});
I think this should work
if(!localStorage.getItem("firstTime")){
//code executed first time
localStorage.setItem("firstTime","true");
}else{
//code executed 2th 3th etc.
}
That could be executed after some event, like click or onload. Keep in mind that you could store whatever you want with localStorage.
There are multiple ways to achieve this depending on your exact requirement.
If you want to handle it once per session, then you can have a session variable and handle it.
If you want to handle it once per user agent, then you can use either local storage or cookies to handle it.
refer this for more info.
Related
I have a problem. It is my full honor if anyone helps.
First, let me explain the workflow I want. My CMS is Wordpress. I have a webpage (views.php). In this page, I want to show a download button (id=” download-button”) just to users who has the role subscriber. In default, no one has the role subscriber. So, the button is hidden in default. When a user buys a specific product he gains the role subscriber. Now, suppose a user has opened views.php page as a tab in his browser. In this step, the button is hidden. After that, he opens another tab and buys that specific product and he gains the role subscriber. Now, if he refresh the view.php page, the download button is seen. But, I want the user to see the download button without refreshing the page. In this regard, I wrote button.php file to be called in ajax. However, it does not work.
My codes:
html code (written in view.php which is the place of download button):
<div id="div1"></div>
my javascript code (which is put inside view.php file):
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("button.php");
});
});
</script>
my button.php code:
<?php
if (check_user_role(array('subscriber'))) {
echo ('<button id="download-button">Download</button>');
}
?>
I should note that I have written check_user_role php function in views.php.
It would be my honor if you help.
Thanks in advance.
Milad
As stated by smartdroid in one of the answers above, you can subscribe an event listener function to the window.onfocus event. Try following:
document.addEventListener("DOMContentLoaded", function (event) {
window.onfocus = function () {
$("#div1").load("button.php");
}
});
I highly recomment you to read further into javascript events.
For plain javascript:
https://www.w3schools.com/js/js_events.asp
For jQuery:
https://api.jquery.com/category/events/
Hey you have to use Window setInterval() Method, what this method does it will fire in background at your time interval set.
You can call your ajax code to set/show your button
setInterval(function(){
$("#div1").load("button.php");
}, 3000);
Make sure once you do add this button put return false so it wont execute again and again not to increase load on webpage.
$(document).ready event runs only once after the DOM is loaded. So this event will not fire unless page is reloaded.
If the user is buying a subscription in another browser tab and then returns to the original tab, windows.onfocus event will fire.
So you can use window.onfocus event to check for subscription every time view.php tab becomes active, and then show the button when necessary. So you can use something like the following, in your view.php
$(document).ready(function(){
window.onfocus = function () {
$("#div1").load("button.php");
}
});
Add an iframe to your view.php that doesn't need to contain anyting nor be visible.
<iframe name="download" id="if_download" src="blank.html"></iframe>
Target the download-action to the iframe. With some JS:
function download(href) {
window.frames['download'].location = 'download.php?file=' + href;
return false;
}
You may need to wrap the download-action through a php-file to modify its header
download.php:
$file_name = $_GET['file'];
//validate file exists and *remove any ../ - simple:
if (strpos($file_name, '/') !== false) die('yeah right..');
header("Content-Disposition: attachment;filename=\"$file_name\"");
echo file_get_contents($file_name);
die();
We want to have a back button in our site
but history.back in javascript does not help us.
We need this function only run on the site and if the user comes from other site, clicking the return button on the previous site should not return.
In fact, we want a return button to run on our site only.
my code is
<i class="fas fa-arrow-left"></i><span class="btn-text">Back</span>
This only works for your own made back button and won't work with the browser back button
There is two ways to achieve that: a simple but not always reliable method and a complex one but always good.
1- The simple method
You use document.referrer and ensure the domain is yours before calling history.back().
2- The complex method
You could register a JavaScript function on page load to get the first URL the internaut land which you could store using history.pushState. Before calling the back function, you could ensure this is not that page. Though, this idea is not complete as the user could probably have landed on this page twice. i.e. Home->Product->Home. I'll let you search for further code that would let you counter this problem.
This code checks the history of back button of the browser on its click event:
$('#backbtn').click(function () {
if (document.referrer.includes(window.location.hostname)) {
window.history.back();
} else {
window.location.href = "/your/path";
}
});
<script type="text/javascript">
confirm("Delete user?.");
window.location.href = "users.php";
</script>
$qqq = mysql_query("DELETE from users WHERE panelistname='$theuser'") or die(mysql_error())
considering the code above, (inside a php file, so no worries with certain syntax errors you might notice) the problem here is that when click cancel on the confirm() dialog box that will show up. the delete action still executes. This question might be considered a double since, yeah, I found some questions relevant to this one but I just can't fixed this one myself.
the one I found codes it something like this:
"if (confirm('Are you...?')) commentDelete(1); return false"
I can't find a way to solve this problem, I don't know which part should I insert the SQL command(delete) in this format. Please someone show me how to do this right. :) thanks!
EDIT: I just saw that Nick Zuber posted a similar answer around 1 minute before I posted mine (actually, while I was writing it :P)
I don't clearly understand what you are trying to do.
You want to show the user a confirm window, and if they click Yes, delete some entry in the database, and if they click No, redirect them to the page 'users.php' ?
If it's what you want to do, then you can't do it like this. You can't use JS conditions with PHP. The PHP code is executed server-side (in the server), whereas the JS code is executed client-side (in the browser). What you would need is to do something like this:
warning: don't use this code, it's unsecure and shouldn't ever be used in a real app, it's just to show you how the whole thing works
(IN USERS.PHP)
if(isset($_GET['delete_dat_user']))
{
$qqq = mysql_query("DELETE from users WHERE panelistname='" . $_GET['delete_dat_user'] . "'") or die(mysql_error());
}
(IN THE WEBPAGE)
if(confirm('u serious u want to delete the user'))
{
window.location = 'users.php?delete_dat_user=theUserName';
}
else
{
nope
}
When your page loads, the PHP on your page will automatically execute, regardless of your JavaScript. Instead, try to prompt the user if they want to delete the account and if they click yes redirect them to a page that has your PHP query.
Also, the confirm function returns a boolean value depending on which option is clicked by the user. Try putting it in an if statement:
if(confirm("Delete user?.")){
window.location.href = "delete_user_page.php";
}else{
// cancel was clicked
}
I am working on chrome extension for facebook. If you use facebook, you know that when you scroll down to the bottom of the news feed/timeline/profile it shows more posts. The extension actually adds a button beside the "like" button. So I need to check if there are more posts to add that button to.
Right now to check if the page has been modified, I use setInterval(function(){},2000).
I want to run a function when the user clicks the button. But this function doesn't work if I put it outside (or even inside) setInterval() – The Koder just now edit
How can I check if the webpage has been modified WITHOUT using a loop?
Example:
$(document).ready(function(){
window.setInterval(function(){
$(".UIActionLinks").find(".dot").css('display','none');
$(".UIActionLinks").find(".taheles_link").css('display','none');
$(".miniActionList").find(".dot").css('display','none');
$(".miniActionList").find(".taheles_link").css('display','none');
//only this function doesn't work:
$(".taheles_link").click(function(){
$(".taheles_default_message").hide();
$(".taheles_saving_message").show();
});
//end
$(".like_link").after('<span class="dot"> · </span><button class="taheles_link stat_elem as_link" title="תגיד תכל´ס" type="submit" name="taheles" onclick="apply_taheles()" data-ft="{"tn":">","type":22}"><span class="taheles_default_message">תכל´ס</span><span class="taheles_saving_message">לא תכלס</span></button>');
$(".taheles_saving_message").hide();
}, 2000);
});
In the future, this extension will use AJAX, so setInterval() can make even more problems for me.
If I understand correctly you want to get a notification when the page's DOM changes. And you want to do this without using the setInterval() function.
As your problem lies within the attaching event handlers to elements that are created after the page has loaded, you might be interested in checking out the jquery.live event attachment technique. I think it will solve your issue.
In general you want the page to throw a mutation event. There is a mutation event spec that might be what you're looking for. Here are some links that might be useful.
http://tobiasz123.wordpress.com/2009/01/19/utilizing-mutation-events-for-automatic-and-persistent-event-attaching/
Detect element content changes with jQuery
$(document).ready(function(){
setInterval('fun()',5000);
fun();
});
function fun()
{
alert(11)
}
I have a page where user needs to enter some data and click save to validate the changes, but my problem is if the user is trying to close the browser window or click on a different link to navigate to a different page..I need to delete all the entries the user has saved so far..
I am doing it the following way
window.onbeforeunload = function()
{
if(confirm('Are you sure you want to navigate'))
{
//Invoke `enter code here`server side method
}
else
{
// return false;
}
}
Everything works fine if he click on Yes, the problem comes when he click on "No"..Even if he click on No..the page unload method is getting called and it is redirected to a different page..but I want it to stay in the same page in same state...can you please help me in achieving this.
Thanks and appreciate your response....
You cannot stop the user from leaving the page. What you can do is alert a message to them, asking if they want to leave or not.
The window.onbeforeunload event should return a string (and only a string). This string will be printed on the alert box made by the browser.
You cannot use your own alert box, or block the user from leaving (or redirect them).
window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
Or with jQuery
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
When a user leaves the page, you can use the onunload event to make an AJAX call (you may need to use async: false here).
Example:
$(window).unload(function(){
$.ajax({
url: '/path/to/page/',
async: false, // this may be needed to make sure the browser doesn't
// unload before this is done
success: function(){
// Do something
}
});
});
NOTE: Instead of doing this, why don't you just save everything when the user is completed? Instead of saving it and then removing it if the user doesn't finish?
First of all: you can't! It's impossible. onbeforeunload only accepts a string as return value and will then close if the user wants that.
But then think about what happens if the computer is being without energy and shuts down? Or the browser will closed by the Task Manager? Or even more "realistic": The internet connection get lost! => Then you got invalid data states too!
You are trying to solve a false problem! Your problem isn't this function, your problem is the state of your formular!
Why do you need some kind of function? Do you saving the data before he clicks on save? Then don't! Or make sure to have another query which detects unfinished data in your database and delete it after a timeout!
onbeforeunload only accepts a string as return value. That string will be displayed by the browser with the option to stay on the page or leave it. But that's ll you can do.
You can use something like this, just call the following function on your page
function noBack() {
window.onbeforeunload = function(){window.history.forward()}
}
this disables Back button if window.history is clean, otherwise it works only first time.