I've 3 divs (#Mask #Intro #Container) so if you click on Mask, Intro gets hidden and Container appears.
The problem is that I just want to load this only one time, not every time I refresh the page or anytime I click on the menu or a link, etc.
How can I do this?
This is the script I'm using for now:
$(document).ready(function(){
$("div#mask").click(function() {
$("div#intro").fadeToggle('slow');
$("div#container").fadeToggle('slow');
$("div#mask").css("z-index", "-99");
});
});
Thank you!
You can try using a simple counter.
// count how many times click event is triggered
var eventsFired = 0;
$(document).ready(function(){
$("div#mask").click(function() {
if (eventsFired == 0) {
$("div#intro").fadeToggle('slow');
$("div#container").fadeToggle('slow');
$("div#mask").css("z-index", "-99");
eventsFired++; // <-- now equals 1, won't fire again until reload
}
});
});
To persist this you will need to set a cookie. (e.g. $.cookie() if you use that plugin).
// example using $.cookie plugin
var eventsFired = ($.cookie('eventsFired') != null)
? $.cookie('eventsFired')
: 0;
$(document).ready(function(){
$("div#mask").click(function() {
if (eventsFired == 0) {
$("div#intro").fadeToggle('slow');
$("div#container").fadeToggle('slow');
$("div#mask").css("z-index", "-99");
eventsFired++; // <-- now equals 1, won't fire again until reload
$.cookie('eventsFired', eventsFired);
}
});
});
To delete the cookie later on:
$.cookie('eventsFired', null);
Just point to an empty function once it has been called.
var myFunc = function(){
myFunc = function(){}; // kill it
console.log('Done once!'); // your stuff here
};
Web pages are stateless in that they don't hold states between page refreshes. When you reload the page it has no clue what has happened in the past.
Cookies to the rescue! You can use Javascript (and jQuery has some nice plugins to make it easier) to store variables on the client's browser. Store a cookie when the mask is clicked, so that when the page is next loaded it never shows.
this code with will work perfect for you and it is the standard way provided by jquery to bind events that you want to execute only once
$(document).ready(function(){
$("div#mask").one('click', function() {
$("div#intro").fadeToggle('slow');
$("div#container").fadeToggle('slow');
$("div#mask").css("z-index", "-99");
});
});
Related
What would be a viable way to accomplish the following:
A website has two pages; Parent page and Inside page. If user came to the Inside page directly by typing in the address or by following a link from a page other than Parent page, then show "foo". If user came to the Inside page from the parent page, then show "bar".
I would need this done in JS if possible. If not, PHP is a secondary choice.
You can get the page the user came from with document.referrer.
So you could implement your solution like this:
if (document.referrer === 'yoursite.com/parentpage') {
// do bar
} else {
// do foo
}
Please try this
This code in second page
jQuery(window).load(function() {
if (sessionStorage.getItem('dontLoad') == null) {
//show bar
}
else{
//show foo
}
});
This code in parent page
jQuery(window).load(function() {
sessionStorage.setItem('dontLoad','true')
});
with php:
There is a simple way is to create a mediator page which redirect to inner page after make a session / cookie.. then if you'll get session / cookie, you show foo & unset session.
if someone directly come from url, no session / cookie found & it show bar..
You can use the document.referrer but this is not always set. You could add a parameter to the URL on the parent page and then check for its existance in the child page
Link on the parent page:
<a href='myChildPage.html?fromParent=1'>My Child Page</a>
JS code on your child page:
var fromParent=false;
var Qs = location.search.substring(1);
var pairs = Qs.split("&");
for(var i = 0; i < pairs.length; i++){
var pos = pairs[i].indexOf('=');
if(pos!==-1){
var paramName = pairs[i].substring(0,pos);
if(paramName==='fromParent'){
fromParent=true;
break;
}
}
}
if(fromParent){
alert("From Parent");
}else{
alert("NOT From Parent");
}
This method isnt 100% foolproof either as users could type in the same URL as your parent page link. For better accuracy check the document.referrer first and if not set use the method i've outlined above
intelligent rendering with jQuery
After using #Rino Raj answer, i noticed it needed improvement.
In javascript, the load() or onload() event is most times much slower,
since it waits for all content and images to load before executing your attached functions.
While an event attached to jQuery’s ready() event is executed as soon as the DOM is fully loaded, or all markup content, JavaScript and CSS, but not images.
Let me explain this basing, on code.
When i used #Rino Raj's code, with load() event, it works but on the second/called page, the content appears before class="hide fade" is added (which I don't really want).
Then i refactored the code, using the ready() event, and yes,
the content that i intended to hide/fade doesn't appear at all.
Follow the code, below, to grasp the concept.
<!-- Parent/caller page -->
<script type="text/javascript">
$(document).ready(function() {
sessionStorage.setItem('dontLoad', 'true');
});
</script>
<!-- Second/called page -->
<script type="text/javascript">
$(document).ready(function() {
if(sessionStorage.getItem('dontLoad') == null) {
$("#more--content").removeClass("hide fade");
} else {
$("#more--content").addClass("hide fade");
}
});
</script>
Here is my problem,i have one google ad that expand on click and return when hit close button..but according to changed conditions what i want is to show expand first and close automatically after certain time and when ever it expanded it should close after certain time..i have done this with jquery but it is refreshing the page for the first time can anyone one help..add is made by using google web designer
here is my jquery code i am sure it wont refresh page abut again it is doing it that's why I was thinking of making custom javascript event and trigger it (core javascript)
<script>
var $j = jQuery.noConflict();
setTimeout(function clo(){
$j('#close_this').trigger('click');
$j('#expanded-page').addClass('ed');
},10000);
// above function to clpse it first time after 10 second
(function(){
$j('.banner').click(function(){
$j('#expanded-page').removeClass('ed');
var cl_chk = $j('#expanded-page').hasClass('ed')
if(!cl_chk){
setTimeout(function clo(){
$j('#close_this').trigger('click');
$j('#expanded-page').addClass('ed');
},10000)
}
})
})()
//this function is for closeing that expando ad after its expanded
</script>
here is the url demo:
demo link asian paints ad
dont know if this can help
jQuery.noConflict() // no need to declare a global variable for jQuery ...
(function ($j) { // ... cause you can pass it here
// i like to declare things once and for all....
var closeAfter10 = function () {
setTimeout(function clo() {
$j('#close_this').trigger('click');
$j('#expanded-page').addClass('ed');
}, 10000);
}
//this will attach the event and start the countdown when all contents on the page are loaded
$j(window).load(function() {
$j('.banner').click(function () {
$j('#expanded-page').removeClass('ed');
var cl_chk = $j('#expanded-page').hasClass('ed')
if (!cl_chk) {
closeAfter10(); // ... so i can use them this way ...
}
});
closeAfter10(); // ... here another use of that thing
);
})(jQuery);
I have created a server control for a login panel.
On this panel I have a textbox for the username and a textbox for the password.
Below that there is the button for login.
I want the button to be disabled if either or both textboxes are empty.
For that I created a function that checks the length of the contents of the textboxes.
function doCheck()
{
var lngth1 = document.getElementById('pnLogin_txtUserName').value.length;
var lngth2 = document.getElementById('pnLogin_txtPassword').value.length;
if (lngth1 > 0 && lngth2 > 0)
{
$('#pnLogin_btLogin').removeAttr('disabled');
} else {
$('#pnLogin_btLogin').attr('disabled','disabled');
}
}
I run this function at the start and on every keyup event.
That works great.
The problem is when the browser starts with the page. It fills in the username and password if they are stored.
When the function is then run, it still disables the button even though there is information in the textboxes.
I tried this:
setTimeout( function()
{
doCheck();
}, 2000);
But after 2 seconds I see the button disabling while seeing my credentials filled in.
If I inspect the element in Chrome, I don't see my credentials in the html code.
So where is it stored? How can I detect this?
You will not see the values in the html as they are not actually in the DOM.
You may access their values using $("#pnLogin_txtUserName").val() and
$("#pnLogin_txtPassword").val().
I would simplify your function and use jQuery specific syntax rather than native javascript.
function doCheck() {
var lngth1 = $("#pnLogin_txtUserName").val().length;
var lngth2 = $("#pnLogin_txtPassword").val().length;
if (lngth1 > 0 && lngth2 > 0) {
$('#pnLogin_btLogin').prop('disabled', false);
} else {
$('#pnLogin_btLogin').prop('disabled', true);
}
}
I also changed your code from .attr to .prop for disabling the input. Find more information with this stackoverflow question
The problem is when the browser starts with the page. It fills in the username and password if they are stored. When the function is then run, it still disables the button even though there is information in the textboxes.
Your code is being executed the moment it is loaded and parsed by the browser. The proper jQuery method is to use whats called .ready() which will execute after jQuery detects the page has finished loading.
$(document).ready( function() {
doCheck();
});
Or more simplified to:
$(function() {
doCheck();
});
detecting change
We can detect when the values get changed by bind an event listener:
$("pnLogin_txtUserName").change(function() {
console.log( 'pnLogin_txtUserName has changed', $(this).val() );
});
If we add a class to your inputs, say .loginElements, then we do things a bit easier and detect several different events:
$(".loginElements").on( 'change keypress', function() {
doCheck();
});
Is there a way I can trace what the user does on the page. Mainly I want to do the following thing: User opens a page, if he does not click anywhere on that page to show a tooltip (i'm using tipsy) guiding him which parts are clickable.
So far I've tried several stuffs:
I have set tipsy to show manually: trigger:manual;
I made a variable that equals false until the user clicks those
clickable items (divs and images)
If the variable is false, show the tooltip (tipsy).
But I'm missing something because this doesn't work. Here is my code.
$(document).ready(function() {
var userClick = false;
function showTooltips() {
$(document).ready(function()) {
if(userClick === false)
$('.nickname .pseudo-white').tipsy('show');
}
setTimeout(showTooltips(), 5000);
});
Try getting rid of the extra call to $(document).ready, and pass the function name to setTimeout rather than calling it with ()
$(document).ready(function() {
var userClick = false;
function showTooltips() {
if(userClick === false)
$('.nickname .pseudo-white').tipsy('show');
}
setTimeout(showTooltips, 5000);
});
For a project I need to print a document using PHP code.
Currently I have a self closing pop up to start the print.
The only problem I have is that a user could spam the button creating a lot of print requests and a huge queue.
The code I have right now:
function newPopup(url) {
popupWindow = window.open(
url,'popUpWindow','height=10,width=100,left=10,top=10,resizable=no,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=no'); // Verstop op achtergrond
popupWindow.blur();
}
Print
I have found some code to stop links but I have problems implementing these since I already call it as a pop up.
You can use a flag:
var flag=true;
function newPopup(url) {
if(flag) {
window.open(...).blur();
flag=false;
window.setTimeout(function(){flag=true;},5*1000);
}
}
Not a "good" solution (uses a global variable), but it should work.
You may disable the link before you open the popup and then re-enable it after five seconds. The problem is that to enable/disable a link can't be done in a very portable way. To workaround this you have to save the actual link, replace it with a fake one and then re-enable it later (when interval elapsed). Like this:
function newPopup(url) {
// Save current link and replace it with a fake one
var oldLink = $("#linkid").attr("href");
$("#linkid").attr("href", "#");
setinterval(function() {
// Restore true link
$("#linkid").attr("href", oldLink);
}, 5000);
// ...
}
You can extract this code to a separate function temporaryDisableLink(id, timeout) to reuse it for many different links (without polluting all other code).
Now let's explore other solutions.
Your HTML code must be updated to (in case you want to reuse the same function for many links otherwise you do not need to pass the link id parameter) to:
<a id="link-print"
href="JavaScript:newPopup('#link-print', 'print.php');">
Print
</a>
The pointer-events CSS property isn't supported by IE (and Opera) so I can't suggest to use it in real world. Anyway it's:
function newPopup(id, url) {
$(id).css("pointer-events", "none");
setinterval(function() {
$(id).css("pointer-events", "auto");
}, 5000);
// ...
}
Because you're using JavaScript to open the pop-up you may consider to change a little bit the function to use a custom disabled attribute (or to check for pointer-events if you plan to use them together):
function newPopup(id, url) {
if ($(id).attr("disabled") == "disabled") {
return false;
}
$(id).attr("disabled", "disabled");
setinterval(function() {
$(id).removeAttr("disabled");
}, 5000);
// ...
}
<script>
function newPopup(url) {
setTimeout(function () {
popupWindow = window.open(
url, 'popUpWindow', 'height=10,width=100,left=10,top=10,resizable=no,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=no'); // Verstop op achtergrond
popupWindow.blur();
},5000
);
}
</script>
Print