Use Cookies to prevent user clicking link twice - javascript

I am trying to prevent the class .activeAdv being added if the link within has it's URL stored in cookie, this cooke is added if user clicks links so basically I am trying to stop returning users clicking same link twice.
The link is by default hidden underneath a div which animates on addition of .activeAdv class, revealing link.
Current code is below along with codepen example of project. I'm guessing I need to wrap the activeAdv addClass in an IF conditional which:
Gets value of child link's href
Check to see if a matching cookie exists
Only add .activeAdv if condition returns false
I think I have the right idea and have got as far as setting cookie on click of link, I am struggling with the IF statement though, could anyone lend a hand?
http://codepen.io/Jambob/pen/wKyoRr
<article>
<div id="on-1" class="box">
<h2>1 dec</h2>
</div>
<div class="present">
content
www.google.com
</div>
</article>
// Checks for content within .present, if TRUE adds .activeAdv animation class
$(".present").filter(function(){
return $(this).html().trim().length > 0;
}).parent().addClass('activeAdv');
// When link clicked, store its URL in cookie
$( ".present a" ).click(function() {
$.cookie($(this).attr('href'), true);
});
if ( '(".present").html().trim().length > 0;' ) {
if ( '(".present a").attr("href")' === "http://www.google.com") {
$(this).parent().addClass('activeAdv');
}
}
After a bit of thinking I have come up with a different IF statement which may be along the right lines
// Checks if content exists
if ( '(".present").html().trim().length > 0;' ) {
// Checks if HREF of child link matches existing cookie (using a string for testing)
if ( '(".present a").attr("href")' === "http://www.google.com") {
$(this).parent().addClass('activeAdv');
}
}

So if :visited CSS pseudoclass isn't sufficient (it matches visited links), you can make use of localStorage, which is much more dedicated to this purpose. I created script which can be run out the Firebug console and colors non-visited links:
(function(links) {
// Load visited links from local storage
var visited = JSON.parse(localStorage["visited"]||"[]");
// Safety check
if(!visited instanceof Array) {
visited = [];
localStorage["visited"] = [];
}
function setClassToLinks() {
links.each(function(){
// Remember state - asume not visited
var linkVisited = false;
// Check for inner HTML
if(this.innerHTML.trim().length > 0) {
// Check if in list of visited links
if(visited.indexOf(this.href)==-1)
linkVisited = true;
else
console.log("Already visited: "+this.href);
}
else
// Skip empty links
return console.log("No inner HTML.");
// Reset color
this.style.color = !linkVisited?"":"red";
// And remove class
if(linkVisited)
$(this).removeClass("activeAdv");
else
$(this).addClass("activeAdv");
})
}
setClassToLinks();
// When link clicked, store its URL in LocalStorage
links.click(function() {
// Prevent duplicities
if(visited.indexOf(this.href)==-1) {
visited.push(this.href);
localStorage["visited"] = JSON.stringify(visited);
}
});
// [OPTIONAL] Update links realtime - triggers when local storage changes
window.addEventListener('storage', function (event) {
if(event.key=="visited") {
visited = JSON.parse(localStorage["visited"]||"[]");
// Change CSS
setClassToLinks();
}
});
})($("a"));
Neat aspect of my solution is, that the links automatically update when you browse in different tab (provided this tab has run the script).
The visited array may quickly grow, which is why I think cookie is such a bad idea.

Related

Switching style between two elements on photo gallery change

So I have a photo gallery on my front page that switches between two images; each image links to a different page. Now, beside that gallery I have two links that go to the same two pages. The idea is that when image A is showing, side-link A should be highlighted with a border. The issue I keep running into is that once I get either side-link to be highlighted, I don't really know how to get it unhighlighted. Instead of switching with the images, they just stay highlighted.
var debugLink = "#firstLink";
function displayNextImage()
{
index++;
if(index >= indexgalpics.length)
{
index=0;
}
//---this is where I set the var debugLink which is
// supposed to carry the selected linke
if(index == 0)
{
console.log("first link selected");
//---when image A is showing, top side-link should be highlighted
//---ok so we know this much works, it seems these double equal
// signs are very important here.
//---makeActive();
//---but once makeActive() is called here, it makes the first link
// active for the entire time.
//---we can't put the entire style code here because same as before,
// it just keeps the link highlighted forever
debugLink = "#firstLink";
//---ok so i can set a var at top to a value in the makeActive() function,
// but i think the way JS works highlights either one forever
debugLink = "#firstLink";
}
else if(index == 1)
{
console.log("second link should be selected");
//---when image B is showing, bottom side-link should be highlighted
debugLink = "#secondLink";
}
showImg();
}
function makeActive()
{
var activeLink = document.querySelector(debugLink);
//---adds style to the debugLink
}
The function makeActive() is called in the function showImg(), and the function displayNextImage() is called in another function that sets the timer.
I changed your approach a little bit by using a boolean for the index, because you seem to only need two states.
Here is a revised version:
Note: In this code, I've used custom-made functions to make the code easier to read. I created hasClass(el,class), addClass(el,class), removeClass(el,class), toggleClass(el,class,bool). You can find them in the final JS Fiddle.
// Register the link elements
var links = {
true : document.getElementById('firstLink'),
false : document.getElementById('secondLink')
},
// Keep track of selected link (replaces your 'index')
leftLinkActive = false,
// Just so you don't go get it every time
gallery = document.getElementById('gallery');
// Let's trigger the gallery
displayNextImage();
// We'll change the active link and show the correct image
function displayNextImage(){
leftLinkActive = !leftLinkActive;
if(leftLinkActive){ console.log("first link selected"); }
else{ console.log("second link selected"); }
makeActive();
showImg();
// Let's do that again in 2 seconds
setTimeout(displayNextImage,2000);
}
// Add / remove the active class
function makeActive(){
addClass( links[ leftLinkActive ], 'active-class');
removeClass( links[ !leftLinkActive ], 'active-class');
}
// Change the image with a small fadeOut transition
function showImg(){
addClass(gallery,'fadeOut');
setTimeout(function(){
// Here we switch from img1 and img2
gallery.style.backgroundImage = 'url('+(leftLinkActive?'im1.jpg':'im2.jpg')+')';
removeClass(gallery,'fadeOut');
},200);
}
JS Fiddle Demo

Applying .click event only to links in a certain div-container

The code already creates a navigation based on a JSON-file. The url are accessible by writing data.chapter[].subchapter[].url, the according title through data.chapter[].subchapter[].title
In case you are interested in that part or want the complete code, I uploaded it there: http://fabitosh.bplaced.net/SkriptET_iFrame_v2/
The goal now is to create a right sidebar which shows the links to the next and previous files in the structure. My approach is below.
What confuses me, is that back() is called until subchap is zero, when a link in #left is being clicked on. It should only be called when the previous-link is being clicked on. What do I have to change in order to achieve that?
Thanks a lot already!
var chap; //position in the array of the currently open chapter
var subchap; //position in the array of the currently open subchapter
function update_right() {
var path = data.chapter[chap].subchapter;
//Previous Page
if(subchap > 0) {
$("#prev").html("<b>Previous:</b><a href='"+path[subchap-1].url+"'>"+path[subchap-1].title+"</a><br/>");
$("#prev > a").click(back());
} else { //subchap == 0
$("#prev").html("");
};
}
function back() {
subchap--;
update_right();
}
$(document).ready(function() // DOM needs to exist in order to be able to add stuff in there
{
...Navigation being built up...
//------ onClick Navigation
$('#left > ul > li > a').click(
function(e)
{
chap = $(this).attr("data-chap");
subchap = $(this).attr("data-subchap");
update_right();
}
);
});

YUI Library - Best way to keep global reference to object?

I'm trying to use the yahoo ui history library. I don't see a great way to avoid wrapping all my function contents with the Y.use so that I can get access to the history object. I tried declaring it globally outside of the use() command, but this didn't seem to work. If you look at my showDashboard() and showReport1() methods, you can see I'm wrapping the contents, which seems redundant to have to do this for every function that uses the history. Is there a better way to do this?
All of the yahoo examples I've seen don't se functions at all and keep the entire sample inside a single use method.
<div>
Dashboard |
Report 1
</div>
<script type="text/javascript">
// Global reference to Yahoo UI object
var Y = YUI();
function showDashboard() {
Y.use('*', function (Y) {
var history = new Y.HistoryHash();
history.addValue("report", "dashboard");
});
}
function showReport1() {
Y.use('*', function (Y) {
var history = new Y.HistoryHash();
history.addValue('report', "report1");
//var x = { 'report': 'report1', 'date': '11/12/2012' };
//history.addValue("report", x);
});
}
Y.use('history', 'tabview', function (Y) {
var history = new Y.HistoryHash();
var tabview = new Y.TabView({ srcNode: '#demo' });
// Render the TabView widget to turn the static markup into an
// interactive TabView.
tabview.render();
// Set the selected report to the bookmarked history state, or to
// the first report if there's no bookmarked state.
tabview.selectChild(history.get('report') || 0);
// Store a new history state when the user selects a report.
tabview.after('selectionChange', function (e) {
// If the new tab index is greater than 0, set the "tab"
// state value to the index. Otherwise, remove the "tab"
// state value by setting it to null (this reverts to the
// default state of selecting the first tab).
history.addValue('report', e.newVal.get('index') || 0);
});
// Listen for history changes from back/forward navigation or
// URL changes, and update the report selection when necessary.
Y.on('history:change', function (e) {
// Ignore changes we make ourselves, since we don't need
// to update the selection state for those. We're only
// interested in outside changes, such as the ones generated
// when the user clicks the browser's back or forward buttons.
if (e.src === Y.HistoryHash.SRC_HASH) {
if (e.changed.report) {
// The new state contains a different report selection, so
// change the selected report.
tabview.selectChild(e.changed.report.newVal);
} else if (e.removed.report) {
// The report selection was removed in the new state, so
// select the first report by default.
tabview.selectChild(0);
}
}
if (e.changed.report) {
alert("New value: " + e.changed.report.newVal);
alert("Old value: " + e.changed.report.prevVal);
}
});
});
</script>
</form>
</body>
</html>
Instead of using plain function on click, attach handlers with YUI.
If you can change the HTML code - add id or class to the links, for example
<a id="btnShowDashboard" href="#">Dashboard</a>
Then in your use() add click handler to the buttons
Y.use('history', 'tabview', 'node', 'event', function (Y) {
var bntShowDashboard = Y.one('#btnShowDashboard');
if (bntShowDashboard) {
bntShowDashboard.on('click', function(e) {
e.preventDefault();
var history = new Y.HistoryHash();
history.addValue("report", "dashboard");
});
}
...
})
That way you will be sure than on the moment of execution "history" is loaded.
BUT there is one drawback - until YUI modules are loaded, if you click the links nothing will happen.

jQuery conditionally change events depending on .html( 'string' ) values

http://jsfiddle.net/motocomdigital/Qh8fL/4/
Please feel free to change the heading if you think I've worded it wrong.
General
I'm running a wordpress site with multilingual control. And my menu/navigation is dynamic, controlled via the wordpress admin. The multilingual language plugin also changes the dynamic menu/navigation content, as well as page content.
My Contact button, which is in the dynamic navigation, opens a sliding menu using jQuery. Very simple animation using top css. The contact button is on the page twice, hence why I'm not using the .toggle for iterations. See jsFiddle.
Script
var $button = $(".contact-button"),
// var for button which controls sliding div
$slide = $("#content-slide");
// var for the div which slides up and down
$button.on('click', function () {
// function for when button is clicked
if ($button.html() == 'Close') {
// run this if button says 'Close'
$slide.stop().animate({ top: "-269px" }, 300);
// close slide animation
$button.html('Contact');
// change text back to 'Contact'
} else {
// else if button says Contact or anything else
$slide.stop().animate({ top: "0" }, 300);
// open slide animation
$button.html('Close');
// change text to 'Close'
}
});
Problem
Because I'm running multilingual on the site. The navigation spelling changes. See jsFiddle flag buttons for example. This is fine, the animation still runs OK, because it's using the button class 'contact-button'.
But because I'm using the .html to replace the text of the button to "Close" and then on the second iteration, back to "Contact" - obviously this is a problem for other languages, as it always changes to English 'close' and back to English 'Contact'
But my three languages and words that I need the iterations to run through are...
Contact - Close
Contatto - Cerca
Contacto - Chiudere
Can anyone help me expand my script to accommodate three languages, all my attempts have failed. The jsFiddle has the script.
The language functionality in the fiddle is only for demo purposes, so the iteration sequence can be tested from the beginning. I understand if you change the language whilst the menu is open (in the fiddle), it will confused it. But when the language is changed on my site, the whole page refreshes, which closes the slide and resets the sequence. So it does not matter.
Any pro help would be awesome thanks!!!
MY POOR ATTEMPT, BUT YOU CAN SEE WHAT I'M TRYING TO ACHIEVE
var $button = $(".contact-button"),
// Var for button which controls sliding div
$slide = $("#content-slide");
// Var for the div which slides up and down
$button.on('click', function () {
// function for when button is clicked
if ($button.html() == 'Close' || 'Cerca'|| 'Chiudere' ) {
// run this if button says Close or Cerca or Chiudere
$slide.stop().animate({ top: "-269px" }, 300);
// Close slide animation
$(function () {
if ($button.html(== 'Close') {
$button.html('Contact'); }
else if ($button.html(== 'Cerca') {
$button.html('Contatto'); }
else ($button.html(== 'Chiudere') {
$button.html('Contacto'); }
});
// Change text back to Contact in correct language
} else {
// else if button says Contact or anything else
$slide.stop().animate({ top: "0" }, 300);
// Open slide animation
$(function () {
if ($button.html(== 'Contact') {
$button.html('Close'); }
else if ($button.html(== 'Contatto') {
$button.html('Cerca'); }
else ($button.html(== 'Contacto') {
$button.html('Chiudere'); }
});
// Change text back to Close in the correct language
}
});
See my attempt script above which is not working on this jsFiddle.
Here's a working example: http://jsfiddle.net/Qh8fL/2/
When one of the language buttons gets clicked, it stores the strings for Contact and Close using jQuery's .data() method. Then, when the contact/close button gets clicked, it refers to those strings rather than having it hard-coded.
Here are the relevant lines of code:
$("#english").click(function() {
$(".contact-button").html('Contact').data('langTxt',{contact:'Contact',close:'Close'});
});
$("#spanish").click(function() {
$(".contact-button").html('Contatto').data('langTxt',{contact:'Contatto',close:'Close'});
});
$("#italian").click(function() {
$(".contact-button").html('Contacto').data('langTxt',{contact:'Contacto',close:'Close'});
});
if ($button.html() == 'Close') {
//...
$button.html($button.data('langTxt').contact);
} else {
//...
$button.html($button.data('langTxt').close);
}
All you need to do to modify the "close" text appropriately is by editing the close property inside the calls to data() that occur in each of the click events.
You should never depend on label strings ... especially in a multilingual environment. Instead you should use placeholders that you store in an attribute (maybe using .data()). Then you write your own setters for the labels depending on the value of the attribute.
var myLabels = {'close': ['Close', 'Cerca', 'Chiudere'], 'contact' : ['Contact', 'Contatto', 'Contacto']};
var currLang = 2; // to select italian
....
// to set the label
$button.data('mylabel', 'close');
$button.html(myLabels['close'][currLang]);
....
if($button.data('mylabel') == 'close') {
$button.data('mylabel', 'contact');
$button.html(myLabels['contact'][currLang]);
} else {
$button.data('mylabel', 'close');
$button.html(myLabels['close'][currLang]);
}

JQuery/Javascript works on & off

I am using JQuery 1.3.2-min in a project to handle JavaScript animations, ajax, etc. I have stored the file on the same server as the site instead of using Google. When I run the site locally on my development machine, everything works fine in FF, IE, Opera, and Safari (all the latest versions - I work from home and I only have 1 machine for personal use and development use) except for some CSS differences between them and when I go to the live site on my machine it works fine also. I have cleared my caches and hard refreshed the page, and it still works.
This is where it gets interesting however. When I send the site to my boss to test in various OS/Browser configurations, one page doesn't work correctly, some of it works, some doesn't. Also, the client (who uses IE 8) has also confirmed that it is not completely working - in fact he has told me that the page will work fine for a hour, and then just "turn off" for a while. I have never heard of this sort of thing before, and google isn't turning too much up. I have a hunch it may partly be with JQuery's .data(), but I'm not sure.
The page is basically nested unordered lists, and three basic actions happen on the list.
The top most unordered list is set to visible (all list via css are set to display: none to keep them hidden on a fresh page request); all list items divs are given a hover action of full opacity on mouseon, and faded back to 50% opacity on mouseoff; and then whenver a paragraph is clicked, the top most unordered list in that list item is displayed.
Here is my Javascript file for the page:
$(function() {
// Set first level ul visible
$('div#pageListing ul:first').css('display', 'block');
// Disable all the hyperlinks in the list
$('div#pageListing li a').click(function() {
var obj;
obj = $(this).parent(0).parent('div:first');
highlight(obj);
return false;
});
// List Item mouse hovering
$('#pageListing li').hover(
// Mouse On
function() {
if ($(this).children('div').attr('id') !== 'activePage') {
$(this).children('div').css('opacity', 1).css('filter',
'alpha(opacity=100)');
}
}, // Mouse off
function() {
if ($(this).children('div').attr('id') !== 'activePage') {
$(this).children('div').css('opacity', 0.4).css('filter',
'alpha(opacity=40)');
}
});
// Active list item highlighting
$('#pageListing li div').click(function() {
highlight($(this));
});
// Sub-list expanding/collapsing
$('#pageListing p.subpageslink').click(function() {
// Get next list
var subTree = $(this).parent('div').next('ul');
// If list is currently active, close it, else open it.
if (subTree.data('active') != true) {
subTree.data('active', true);
subTree.show(400);
} else {
subTree.data('active', false);
subTree.hide(400);
}
});
// Double clicking of list item - edit a page
$('#pageListing li div').dblclick(function() {
var classes = $(this).attr('class');
var classArray = classes.split(' ');
var pageID = classArray[1];
editPage(pageID);
});
// Handle button clicking
$('button#addPage').click(function() {
addPage();
});
$('button#editPage').click(function() {
var div = $('div#activePage');
var classes = div.attr('class');
var classArray = classes.split(' ');
var pageID = classArray[1];
editPage(pageID);
});
$('button#delPage').click(function() {
var div = $('div#activePage')
var classes = div.attr('class');
var classArray = classes.split(' ');
var pageID = classArray[1];
delPage(pageID);
});
});
// Highlighting of page when clicked
function highlight(obj) {
// Get previous hightlighted element
// and un-highlight
var oldElement = $('div#activePage');
oldElement.css('background', 'white');
oldElement.css('opacity', 0.4).css('filter', 'alpha(opacity=40)');
oldElement.removeAttr('id');
// highlight current selection
obj.attr('id', 'activePage');
obj.css('opacity', 1).css('filter', 'alpha(opacity=100)');
obj.css('background', '#9dc0f4');
// add appropiate action buttons
$('button.pageButton').css('display', 'inline');
}
function addPage() {
window.location = "index.php?rt=cms/editPage";
}
function delPage(page) {
var confirm = window.confirm("Are you sure? Any sub-pages WILL BE deleted also.");
if (confirm) {
var url = './components/cms/controller/forms/deletePage.php';
$.ajax( {
url : url,
type : 'GET',
data : 'id=' + page,
success : function(result) {
if (!result) {
document.location = "index.php?rt=cms";
} else {
window.alert('There was a problem deleting the page');
}
}
});
}
}
function editPage(page) {
var url = "index.php?rt=cms/editPage/" + page;
window.location = url;
}
Is it possible that you are linking to (some of) the script files using a src that points to a file on your local disk/HDD? If so, that would explain why it works only on your machine, as then only your machine has access to the script file.
Thank you one and all for your suggestions. The end problem was miscommunication. I work from home, and upload my projects to a SVN server, which the boss then uses to update the live server. Somehow, the correct files were not getting updated - a communication error on my part. Another possible reason was that the page, while being declared XHTML 1.0 Strict, had something like 50 validation errors (mosting incorrectly nested UL), and I cleaned that up to 5 errors. So thank you all, but again a sad example of the importance of team work communication.

Categories

Resources