Change HTML Button Based On Cookie Existance - javascript

I want to edit an html button that will tell the user if they have read the page that the button is on. The button is at the bottom of the page, and starts off being red. After the user presses the button, a cookie is generated and the changeButton() function checks to see if the cookie has been created, and then changes the button to green. Even after the user closes and reopens the browser, the button should stay green until the cookie has been deleted.
My browser just shows the button as being green on page loadup, before I even hit the button. Any help would be greatly appreciated.
<head>
<script type="text/javascript">
function changeButton()
{
var name = 'user_read_the_page' + '=';
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i];
while(c.charAt(0)==' ')
{
c = c.substring(1);
}
if(c.indexOf(name) != -1)
{
var output = c.substring(name.length,c.length);
}
}
document.getElementById("test").innerText = output;
if(output == 1)
{
cookie_exists = 1;
}
else
{
cookie_exists = 0;
}
if(cookie_exists == 1)
{
document.getElementById("read_button").style.backgroundColor = "green";
document.getElementById("read_button").style.color = "white";
document.getElementById("read_button").style.fontWeight = "bold";
document.getElementById("read_button").innerText = "\u2714 You Have Read This Page";
}
else
{
document.getElementById("read_button").style.backgroundColor = "red";
document.getElementById("read_button").style.color = "white";
document.getElementById("read_button").style.fontWeight = "bold";
document.getElementById("read_button").innerText = "\u2718 Please Read This Page";
}
return "";
}
</script>
</head>
...
<button id="read_button" onclick="createCookie('user_read_the_page', 30)"></button>
<script language="javascript">
function createCookie(name, days)
{
var expire = new Date ();
expire.setTime (expire.getTime() + (24 * 60 * 60 * 1000) * days);
document.cookie = name + "=1; expires=" + expire.toGMTString();
changeButton();
}
</script>

Related

SpeechSynthesisUtterance script with play, pause, stop buttons and selection of language and voice

I would like to read the text of my pages with SpeechSynthesisUtterance.
I found this script: https://www.hongkiat.com/blog/text-to-speech/
Almost perfect, but the pause button doesn't seem to do much, and I wish I had the ability to set a language and maybe choose a voice.
I found the reference here: https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance, but I'm not very knowledgeable in JavaScript.
For language, as far as I understand, should be used the lang parameter set in the html tag.
For the voice I have absolutely no idea of how to implement it in the code.
It would be important because I have texts in English, Spanish, French and Italian, and the result without voice and language settings sometimes sounds really weird.
Update
These days I fiddled a little, I managed (more or less) to combine two different scripts/examples.
This: https://www.hongkiat.com/blog/text-to-speech/
and this: https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis#Examples
The code that came out is this:
HTML
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="text-to-speech.js"></script>
</head>
<body>
<div class=buttons>
<button id=play></button>
<button id=pause></button>
<button id=stop></button>
</div>
<select id="voices">
</select>
<div id="description">
The SpeechSynthesis interface of the Web Speech API is the controller interface for the speech service; this can be used to retrieve information about the synthesis voices available on the device, start and pause speech, and other commands besides.
Questo è in italiano come viene?
</div>
</body>
</html>
CSS
#import url('https://fonts.googleapis.com/css?family=Crimson+Text');
.buttons {
margin-top: 25px;
}
button {
background: none;
border: none;
cursor: pointer;
height: 48px;
outline: none;
padding: 0;
width: 48px;
}
#play {
background-image: url(https://rpsthecoder.github.io/js-speech-synthesis/play.svg);
}
#play.played {
background-image: url(https://rpsthecoder.github.io/js-speech-synthesis/play1.svg);
}
#pause {
background-image: url(https://rpsthecoder.github.io/js-speech-synthesis/pause.svg);
}
#pause.paused {
background-image: url(https://rpsthecoder.github.io/js-speech-synthesis/pause1.svg);
}
#stop {
background-image: url(https://rpsthecoder.github.io/js-speech-synthesis/stop.svg);
}
#stop.stopped {
background-image: url(https://rpsthecoder.github.io/js-speech-synthesis/stop1.svg);
}
JAVASCRIPT
onload = function() {
if ('speechSynthesis' in window) with(speechSynthesis) {
// select voices////
var synth = window.speechSynthesis;
var voiceSelect = document.querySelector('#voices');
var voices = [];
function populateVoiceList() {
voices = synth.getVoices().sort(function (a, b) {
const aname = a.name.toUpperCase(), bname = b.name.toUpperCase();
if ( aname < bname ) return -1;
else if ( aname == bname ) return 0;
else return +1;
});
var selectedIndex = voiceSelect.selectedIndex < 0 ? 0 : voiceSelect.selectedIndex;
voiceSelect.innerHTML = '';
for(i = 0; i < voices.length ; i++) {
var option = document.createElement('option');
option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
if(voices[i].default) {
option.textContent += ' -- DEFAULT';
}
option.setAttribute('data-lang', voices[i].lang);
option.setAttribute('data-name', voices[i].name);
voiceSelect.appendChild(option);
}
voiceSelect.selectedIndex = selectedIndex;
}
populateVoiceList();
if (speechSynthesis.onvoiceschanged !== undefined) {
speechSynthesis.onvoiceschanged = populateVoiceList;
}
//end select voices
var playEle = document.querySelector('#play');
var pauseEle = document.querySelector('#pause');
var stopEle = document.querySelector('#stop');
var flag = false;
playEle.addEventListener('click', onClickPlay);
pauseEle.addEventListener('click', onClickPause);
stopEle.addEventListener('click', onClickStop);
function onClickPlay() {
if (!flag) {
flag = true;
utterance = new SpeechSynthesisUtterance(document.querySelector('#description').textContent);
//utterance.voice = getVoices()[0];
//add voice//
var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
for(i = 0; i < voices.length ; i++) {
//if(voices[i].name === 'Google UK English Female') {
if(voices[i].name === selectedOption) {
utterance.voice = voices[i];
break;
}
}
voiceSelect.onchange = function(){
onClickStop();
stopEle.className = '';
onClickPlay();
playEle.className = 'played';
}
//and add voice
utterance.onend = function() {
flag = false;
playEle.className = pauseEle.className = '';
stopEle.className = 'stopped';
};
playEle.className = 'played';
stopEle.className = '';
speak(utterance);
}
if (paused) { /* unpause/resume narration */
playEle.className = 'played';
pauseEle.className = '';
resume();
}
}
function onClickPause() {
if (speaking && !paused) { /* pause narration */
pauseEle.className = 'paused';
playEle.className = '';
pause();
}
}
function onClickStop() {
if (speaking) { /* stop narration */
/* for safari */
stopEle.className = 'stopped';
playEle.className = pauseEle.className = '';
flag = false;
cancel();
}
}
}
else { /* speech synthesis not supported */
msg = document.createElement('h5');
msg.textContent = "Detected no support for Speech Synthesis";
msg.style.textAlign = 'center';
msg.style.backgroundColor = 'red';
msg.style.color = 'white';
msg.style.marginTop = msg.style.marginBottom = 0;
document.body.insertBefore(msg, document.querySelector('div'));
}
}
Now I have the play, stop and pause buttons (pauses still does not work) and I can select one of the voices from those available in the device.
Seems to work fine with chrome, maybe a little less with Firefox, (but I'm using Linux LMDE, maybe it's my fault). And after a while on Chrome stops talking. I don't know why, but it seems to me that I've seen someone maybe understand why in some of the thousands of web pages I've opened these days, I'll have to reopen them all.
It would be nice if the selected voice was saved in a cookie, so if I open another page the script starts with the last voice I selected (I have no idea how to do it in JavaScript)
Update 2
I made some other small steps forward and simplified.
It almost seems to work, not always the pause button, the big doubt I have now is that with chrome it does not seem to stop when I update or change pages, and it is really bad that when you change page he keeps reading the previous page.
HTML
<div id="SpeechSynthesis">
<div>
<button id=play>play</button>
<button id=pause>pause</button>
<button id=stop>stop</button>
</div>
<select id="voices">
</select>
</div>
<p id="texttospeech">
The SpeechSynthesis interface of the Web Speech API is the controller interface for the speech service; this can be used to retrieve information about the synthesis voices available on the device, start and pause speech, and other commands besides.
Questo è in italiano come viene?
</p>
JAVASCRIPT
onload = function() {
if ('speechSynthesis' in window){
var synth = speechSynthesis;
var flag = false;
//stop when change page ???(not sure)
if(synth.speaking){ /* stop narration */
/* for safari */
flag = false;
synth.cancel();
}
/* references to the buttons */
var playEle = document.querySelector('#play');
var pauseEle = document.querySelector('#pause');
var stopEle = document.querySelector('#stop');
/* click event handlers for the buttons */
playEle.addEventListener('click', onClickPlay);
pauseEle.addEventListener('click', onClickPause);
stopEle.addEventListener('click', onClickStop);
// select voices////
//var synth = window.speechSynthesis;
var voiceSelect = document.querySelector('#voices');
var voices = [];
function populateVoiceList() {
voices = synth.getVoices().sort(function (a, b) {
const aname = a.name.toUpperCase(), bname = b.name.toUpperCase();
if ( aname < bname ) return -1;
else if ( aname == bname ) return 0;
else return +1;
});
var selectedIndex = voiceSelect.selectedIndex < 0 ? 0 : voiceSelect.selectedIndex;
voiceSelect.innerHTML = '';
for(i = 0; i < voices.length ; i++) {
var option = document.createElement('option');
option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
if(voices[i].default) {
option.textContent += ' -- DEFAULT';
}
option.setAttribute('data-lang', voices[i].lang);
option.setAttribute('data-name', voices[i].name);
voiceSelect.appendChild(option);
}
voiceSelect.selectedIndex = selectedIndex;
}
populateVoiceList();
if (speechSynthesis.onvoiceschanged !== undefined) {
speechSynthesis.onvoiceschanged = populateVoiceList;
}
//end select voices
function onClickPlay() {
if(!flag){
flag = true;
utterance = new SpeechSynthesisUtterance(document.querySelector('#texttospeech').textContent);
//utterance.voice = synth.getVoices()[0];
//add voice//
var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
for(i = 0; i < voices.length ; i++) {
//if(voices[i].name === 'Google UK English Female') {
if(voices[i].name === selectedOption) {
utterance.voice = voices[i];
break;
}
}
voiceSelect.onchange = function(){
onClickStop();
onClickPlay();
}
//and add voice
utterance.onend = function(){
flag = false;
};
synth.speak(utterance);
//fix stop after a while bug
let r = setInterval(() => {
console.log(speechSynthesis.speaking);
if (!speechSynthesis.speaking) {
clearInterval(r);
} else {
speechSynthesis.resume();
}
}, 14000);
//end fix stop after a while bug
}
if(synth.paused) { /* unpause/resume narration */
synth.resume();
}
}
function onClickPause() {
if(synth.speaking && !synth.paused){ /* pause narration */
synth.pause();
}
}
function onClickStop() {
if(synth.speaking){ /* stop narration */
/* for safari */
flag = false;
synth.cancel();
}
}
}
else {
msg = document.createElement('h5');
msg.textContent = "Detected no support for Speech Synthesis";
msg.style.textAlign = 'center';
msg.style.backgroundColor = 'red';
msg.style.color = 'white';
msg.style.marginTop = msg.style.marginBottom = 0;
document.body.insertBefore(msg, document.querySelector('#SpeechSynthesis'));
}
}
Update 3
I tried to add a cookie with the last selected voice. I added a couple of functions to manage the cookies, and I set the cookie in the onClickPlay() function.
//add voice//
var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
for(i = 0; i < voices.length ; i++) {
//if(voices[i].name === 'Google UK English Female') {
if(voices[i].name === selectedOption) {
utterance.voice = voices[i];
setCookie('SpeechSynthesisVoice',voices[i].name,30);
break;
}
}
Firefox sets the cookie without problems, chrome no (even if the file is on an online server).
Then I tried to set the voice saved in the cookie as "selected" in populateVoiceList() function:
//get cookie voice
var cookievoice = getCookie('SpeechSynthesisVoice');
//add selcted to option if if cookievoice
if (cookievoice === voices[i].name) {
option.setAttribute('selected', 'selected');
}
It works, I find the "selected" in the code, but it doesn't seem to be considered, it always starts talking with the first voice in the list, or the default one, I'm not sure, and not with the one that has the "selected".
The cookie functions I use:
//cookie functions
function setCookie(name, value, days) {
var expires = '',
date = new Date();
if (days) {
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
document.cookie = name + '=' + value + expires + '; path=/';
}
function getCookie(name) {
var cookies = document.cookie.split(';'),
length = cookies.length,
i,
cookie,
nameEQ = name + '=';
for (i = 0; i < length; i += 1) {
cookie = cookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
function eraseCookie(name) {
createCookie(name, '', -1);
}
I didn't receive much help, but somehow I managed to set up a small player that reads the text of a web page.
I did a little tutorial with a demo that explains what I did and how it works.
https://www.alebalweb-blog.com/85-text-to-speech-player-with-buttons-play-pause-stop-and-voice-choice.html
How about this line after the "for" loop?
voiceSelect.selectedIndex = selectedIndex;
If it's still here you're overriding your selection.
Try something like
if(cookievoice === voices[i].name) {
option.setAttribute('selected', 'selected');
selectedIndex = i;
}

How to only show pop up on first page load

I am trying to only display a pop up on the first page load, but in my current script it only shows the pop up if you refresh the page. The popup should display the first time you come to the page but not again.
<script type="text/javascript">// <![CDATA[
document.addEventListener('DOMContentLoaded', function() {
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return '';
}
$(document).ready(function() {
if(getCookie('popup') !== ''){
$('.popup-wrapper').css('display','block');
} else {
setCookie('popup','open',1);
}
$('.popup-close').click(function(){
setCookie('popup','close',1);
$('.popup-wrapper').css('display','none');
});
});
});
// ]]></script>
Any help would be greatly appreciated.
Is there a reason why you are using cookies?? If not you can use localStorage and write something a bit cleaner..
So for example
$(document).ready(function() {
// if localStorage doesnt have the shownPopUp item
if(!localStorage.getItem('shownPopUp')){
$('.popup-wrapper').css('display','block');
}
$('.popup-close').click(function(){
// set the shownPopUp item in localStorage
localStorage.setItem('shownPopUp', true)
$('.popup-wrapper').css('display','none');
});
});
});
No need for the getCookie function
Cookies are more used for server-side functions, where localStorage is better for client-side functions. So what will happen here is your users will never see the popup again unless they delete there localStorage
Just add localStorage.setTtem after showing the popup. And don't forget to make the .popup-wrapper display:none
if(!localStorage.getItem('shownPopUp')){
$('.popup-wrapper').css('display','block');
localStorage.setItem('shownPopUp', true);
}

How to hide a DIV when reloading a page?

I have a loading overlay that shows some information and I have a button to refresh the page. But I want the loading overlay only to appear once, not every time the button is clicked. (F5 doesn't matter). I was thinking of something like this:
<button type="button" onclick="reload();">
function reload() {
if (window.location.reload()) {
document.getElementById('loading').style.display = 'none';
}
}
But it doesn't work... pls help
You can make use of client cookie, set a flag to client cookie if overlay already shown once, example code:
Vanilla JS Version
<script>
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
if (getCookie('OVERLAY_ALREADY_SHOWN')) {
document.getElementById('loading').style.display = 'none';
}
else {
// ... some conditions ...
setCookie('OVERLAY_ALREADY_SHOWN', true, 14); // persist two weeks
}
</script>
jQuery Cookie Version
<script src="/path/to/jquery.cookie.js"></script>
<script>
if ($.cookie('OVERLAY_ALREADY_SHOWN')) {
document.getElementById('loading').style.display = 'none';
}
else {
// ... some conditions ...
$.cookie('OVERLAY_ALREADY_SHOWN', true, { expires: 14 }); // persist two weeks
}
</script>

add cookie if no cookie of that name exists jquery

I have a splash page where the user chooses between 2 experiences. once chosen, a cookie is added so they will always get that experience (or at least for the next 30 days). however, if a user comes to the site directly to a sub-url and bypasses the splash page, they should be automatically added to the default experience and get the default cooke (theme1). everything except the default cookie part is working.
here's what i have:
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
$('.theme2').click(function() {
createCookie('chooseTheme','chosenTheme2',30)
});
$('.theme1').click(function() {
createCookie('chooseTheme','chosenTheme1',30)
});
var x = readCookie('chooseTheme');
if ($.cookie('chooseTheme') === null) {
createCookie('chooseTheme','chosenTheme1',30);
}
if (x.indexOf('chosenTheme1') > -1) {
$('body').addClass('themeOne');
} else if (x.indexOf('chosenTheme2') > -1) {
$('body').addClass('themeTwo');
}
thanks!
Try running a loop that updates every 1 minute. During the update, it triggers the function that checks for the cookie like the following:
setInterval(checkCookie(), 60000);
//the 60000 is for 60000 milliseconds which is 1 minute.
function checkCookie() {
var x = readCookie('chooseTheme');
if ($.cookie('chooseTheme') === null) {
createCookie('chooseTheme','chosenTheme1',30);
}
if (x.indexOf('chosenTheme1') > -1) {
$('body').addClass('themeOne');
} else if (x.indexOf('chosenTheme2') > -1) {
$('body').addClass('themeTwo');
}
}
Then add the code above into your code and it will check for the theme every 1 minute. I hope this helps you.

Run same js code on every page in website

I'm trying to create a popup that opens after 30 seconds even if the user changes to a different page on the site.
e.g. User enters example.com and stays on the main page for 15 seconds, then navigates to a different page still on the site example.com, stays there for 15 seconds. Now I want the popup to open.
My JavaScript code to create a cookie:
<html>
<head>
<script>
var timeElapsed;
var targetTime = 10000;
var myInter;
function openPopup() {
alert('popup');
timeElapsed = 0;
clearInterval(myInter);
setCookie('alreadyDone', true, 1);
}
function updateCookie() {
timeElapsed += 2000;
setCookie('emailPopup', timeElapsed, 1);
alert(timeElapsed);
}
function checkCookie() {
if (getCookie('alreadyDone') === "") {
if (getCookie('emailPopup') === "") {
timeElapsed = 0;
setCookie('emailPopup', timeElapsed, 1);
} else {
timeElapsed = parseInt(getCookie('emailPopup'));
setCookie('emailPopup', timeElapsed, 1);
}
setTimeout(openPopup, targetTime - timeElapsed);
myInter = setInterval(updateCookie, 2000);
}
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
</script>
</head>
<body onload="checkCookie()">
<button>Page 1</button>
</body>
But I need this code run on every page on my site.
1) Create a js file called your-name.js
2) Cut this code and paste there. Save.
3) Call this file in every of your webpages like
<html>
<head>
<script type="text/javascript" src="/your-location/your-name.js"></script>
<head>
<body>
</body>
<html>

Categories