Display message for first time viewer only - javascript

Im trying to display a welcome message for a few seconds then have it fade out and not return (unless user deletes cookies). I know i can do this 2 ways using either js cookies or localStorage. This is the code i'm using:
$(document).ready(function() {
if(localStorage.getItem('messageState') != 'shown'){
$("#message").delay(2000).fadeOut();
localStorage.setItem('messageState','shown')
}
$('#message').fadeOut();
});
});
But it's not fading out. Any ideas what i'm doing wrong?
Or would i be better using js cookie?
Here's a fiddle: http://jsfiddle.net/Y2D67/1786/

Delete your last line, the }); and the fadeout works.
$(document).ready(function() {
if(localStorage.getItem('messageState') != 'shown'){
$("#message").delay(2000).fadeOut();
localStorage.setItem('messageState','shown')
}
$('#message').fadeOut();
});

Your syntax is wrong, the closing bracket
})
does not belong
Localstorage would be a fine way to store something like this, I usually go by the rule that localstorage is for data I want to read on the front end and cookies are primarily for reading server-side

Related

Save dynamic variables on page close

I'm currently building a website for a school project that loads json data into the page dynamically as the user navigates. Here's the code I'm working with right now:
$(function () {
var $divs = $(".divs > div"),
N = $divs.length,
C = 0; // Current
$divs.hide().eq(C).show();
$("#next, #prev").click(function () {
$divs.stop().fadeOut().eq((this.id == 'next' ? ++C : --C) %N).fadeIn();
}); // close click function
}); // close main function
var content = jSONtexts.texts;
$(document).ready(function () {
$("#content0").html(content[0].content);
$("#content1").html(content[1].content);
$("#content2").html(content[2].content);
$("#content3").html(content[3].content);
$("#content4").html(content[4].content);
$("#content5").html(content[5].content);
$("#content6").html(content[6].content);
$("#content7").html(content[7].content);
$("#content8").html(content[8].content);
});
In my html I have divs set up as containers for the particular json data that I want to be presented. It's rudimentary right now, but the user clicks 'next' or 'previous' and a different section of the json loads into the visible div.
What I need is to be able to save what div is showing (maybe using the 'C' variable?) - into a cookie, and load that div when the user returns. I've tried using js.cookie.js, and it's quite possible that I'm using it wrong, Here's what I'm trying:
$( window ).unload(function() {
Cookies.set('pageState', 'C');
}); //close cookie function
But that doesn't seem to be working. It breaks my json loading when I try to put it anywhere in the .js file that would be relevant to the C variable.
I'm stumped. I've looked everywhere on google, and everything that people are saying to try breaks my json function. Help please!
If someone has any ideas I would be eternally grateful!
Thanks
Sam
Cookie is not a best practice to save these data, as cookies will be send with all requests.
Use need to use HTML5 localStorage to save data at client side.
http://www.w3schools.com/html/html5_webstorage.asp
Made demo for the same
document.getElementById("textInput").value = localStorage.getItem("pageState");
window.addEventListener("unload", function() {
localStorage.setItem("pageState", document.getElementById("textInput").value);
});
<input id="textInput" type="text" />
Demo : http://jsfiddle.net/kishoresahas/vvkdge2q/
as #KishoreSahas already suggested in the comments, I would suggest you to use localStorage instead of cookies.
You could store what you need like this
localStorage.setItem("veryimportantdata", "INeedThisLater");
and get it back later like this
var data = localStorage.getItem("veryimportantdata");
console.log(data); // prints out "INeedThisLater"

I want to keep a class changed by jquery across the pages

I'm not sure if this can be done. I'm new on jQuery :)
I have found a way to change a background by clicking an image. But when I refresh the page or change to another page, the background is changed to the original.
Do you know if there is a way to keep the new background selected?
Here is my code:
<script>
$(document).ready(function(){
$("#mood-clasico").click(function(){
$("#chef, #ranchos, #contacto").removeClass("parallax-4, parallax-2");
$("#chef, #ranchos, #contacto").addClass("parallax-1");
});
});
$(document).ready(function(){
$("#mood-chef").click(function(){
$("#chef, #ranchos, #contacto").removeClass("parallax-1, parallax-2");
$("#chef, #ranchos, #contacto").addClass("parallax-4");
});
});
$(document).ready(function(){
$("#mood-kids").click(function(){
$("#chef, #ranchos, #contacto").removeClass("parallax-1, parallax-4");
$("#chef, #ranchos, #contacto").addClass("parallax-2");
});
});
</script>
If you want the state to survive after the window's been closed or page has been navigated away from (to a different domain), use localStorage; otherwise, use sessionStorage (still survives refresh and navigation within the domain). Either way, you'll want to store the css class in a persistent variable and use that to instead of the string, which can help dry the code up a bit too.
Session storage is a little simpler, but your users would probably love you more for using localStorage -- implementation would be something like:
$(document).ready(function() {
var userPref = localStorage.getItem("bg-class") || 'your-default';
$("#chef, #ranchos, #contacto").addClass(userPref);
$("#mood-clasico").click(function(){
swapPref("parallax-4", "parallax-2", "parallax-1");
});
$("#mood-chef").click(function(){
swapPref("parallax-1", "parallax-2", "parallax-4");
});
$("#mood-kids").click(function(){
swapPref("parallax-4", "parallax-2", "parallax-1");
});
function swapPref(out1, out2, inn) {
$("#chef, #ranchos, #contacto")
.removeClass(userPref)
.removeClass(out1)
.removeClass(out2)
.addClass(inn);
localStorage.setItem("bg-class", inn);
}
});
For more persistence (like across different browsers or devices) you'd want to look into the file system api or storing the settings in a database, but based on your question it doesn't seem those options aren't worth the drawbacks. I left out some error handling and things you'd probably want to include, but I'd definitely recommend checking out using the web storage api by mozilla, which actually includes a similar example.
Use the jquery cookie plugin to do this,
details here https://github.com/carhartl/jquery-cookie
then set cookie,
$.cookie("changedBackground", 'true');
and after page refresh this check must be done
if($.cookie("changedBackground")=='true'){
//keep your changed background
}
only with jQuery it's impossible, you have to store the value
try to use session , cockies , external file or data base

pagescroller javascript issue

I'm using PageScroller plugin to scroll to different sections/pages on my website.
Basically I want the scrolling button to return back to the top of the site once it's reached the last page.
I'm trying something like this but it doesn't seem to be working:
$('#controls .next').bind('click', function(e){
if(pageScroller.current ='3'){
pageScroller.goTo(1);
}
else {
pageScroller.next();
}
});
I'm following API's from here http://pagescroller.com/documentation/
Many thanks
On your if statement you seem to be setting the pageScroller.current to 3, try evaluating instead:
if(pageScroller.current == '3'){

Check for empty href atribute in JQuery

I have an idea I'd like to implement to a site I'm working on. I've got an idea of how it would work but I'm not entirely sure how to piece the bits together.
So!! I'd like to check the domain and generate an alert box if it's necessary to do so.
Say we have 2 domains:
test.domain.com & domain.com
IF we're on test.domain.com and there's no content inside the href (Missing Link), I'd like an alert box to pop up saying "MISSING LINK". And if there is content inside the href, just ignore it (Not Missing Link).
Missing Link
Not Missing Link
Then, if we were on domain.com I'd like the jQuery to still be present in the code, but it to do nothing if a Missing Link was clicked. As it will just redirect to the home page - Not the best journey, but much better than an intrusive popup box.
This way I could use a tiny bit of code to check missing links at the test stage, but not have to remove it every time it gets sent to the actual domain.
If any of this doesn't make sense, please ask!
Thanks a million, really appreciate the help!
$(document).on("click", 'a[href=""]', function(evt) {
if(window.location.hostname.indexOf("test")!==-1) {
alert("broken");
} else {
window.location.href = "foo.html";
}
evt.preventDefault();
});
Personally if I were making a page on test to determine if a link is broken, I would do something so they would stand out when the page is open. Instead of clicking to find out.
if(window.location.hostname.indexOf("test")!==-1) {
$('a[href=""]').css("background-color", "red");
}
Here is some code to get you started. It feels to me as though whatever it is you’re trying, we’re taking completely the wrong approach.
if (location.host === 'test.domain.com' && !$('a[href=""]').length) {
alert('MISSING LINK');
}
Hows this?
$(document).ready(function() {
$('a').click(function(e) {
var a = $(this);
e.preventDefault();
if($.trim(a.prop('href')) == "")
{
alert("No link")
}
else
{
window.location = $.trim(a.prop('href'));
}
});
});

How to refresh a Div every 10 seconds without refreshing the entire page?

I'm working on a website platform that doesn't allow for any server sided scripting, so jquery and javascript are pretty much all I have to work with. I am trying to create a script to work with the site that will update a div that contains an inbox message count every 10 seconds. I've been successful with making the div refresh every ten seconds, but the trouble lies in the page views count. My script is refreshing the whole page and counting for a page view, but I only want to refresh just the one div. An example of the trouble my script causes is when viewing anything on the site that has a page view counter (forum posts, blog posts, ect...), the page views go crazy because of the script refreshing. I'm pretty new to Javascript, so I'm not entirely sure there is a way around this.
What I'm working with is below:
<div id="msgalert" style="display: none"; "width: 100px !important">
You have $inbox_msg_count new messages.
</div>
$inbox_msg_count is a call that grabs the message count, and provided by the platform the site is on. It displays the message count automatically when used.
Then the script that does all the work is this:
<script>
setInterval(function(facepop){
var x= document.getElementById("SUI-WelcomeLine-InboxNum");
var z = x.innerText;
if(x.textContent.length > 0)
$("#msgalert").show('slow');
}, 1000);
facepop();
</script>
<script>
setInterval(function() {
$("#msgalert").load(location.href+" #msgalert>*","");
}, 1000); // seconds to wait, miliseconds
</script>
I realize I've probably not done the best job of explaining this, but that's because I'm pretty confused in it myself. Like I mentioned previously, this code function just how I want it, but I don't want it to refresh the entire page and rack up the page views. Any help is much appreciated.
You might try to look into iframe and use that as a way to update/refresh your content (div). First setup an iframe, and give it an id, then with JS grab the object and call refresh on it.
well your prob seems a little diff so i think submitting a from within the div might help you so ...
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../member/uploadTempImage',//serverURL
type:'post',
beforeSend:function()
{
alert(" if any operation needed before the ajax call like setting the value or retrieving data from the div ");
},
success:function(e){
alert("this is the response data simply set it inside the div ");
}
});
});
I think this could probably be done without a form, and definitely without iframes (shudder)..
Maybe something like this?
$(document).ready(function()
{
setInterval(function(facepop)
{
var x= document.getElementById("SUI-WelcomeLine-InboxNum");
var z = x.innerText;
if(x.textContent.length > 0)
$("#msgalert").show('slow');
$.ajax({
type: "POST",
url: location.href,
success: function(msg)
{
$("#msgalert").html(msg);
}
});
},1000);
It's not entirely clear exactly what you're trying to do (or it may just be that I'm ultra tired (it is midnight...)), but the $.ajax() call in the above is the main thing I would suggest.
Encapsulating both functions in a single setInterval() makes things easier to read, and will extinguish the 1 second gap between showing the msgalert element, and "re-loading" it.

Categories

Resources