I have been writing my own Lightbox script (to learn more about jQuery).
My code for the captions are as follows (the problem is that the captions are the same on every image):
close.click(function(c) {
c.preventDefault();
if (hideScrollbars == "1") {
$('body').css({'overflow' : 'auto'});
}
overlay.add(container).fadeOut('normal');
$('#caption').animate({
opacity: 0.0
}, "5000", function() {
$('div').remove('#caption');
});
});
$(prev.add(next)).click(function(c) {
c.preventDefault();
$('div').remove('#caption')
areThereAlts = "";
var current = parseInt(links.filter('.selected').attr('lb-position'),10);
var to = $(this).is('.prev') ? links.eq(current - 1) : links.eq(current + 1);
if(!to.size()) {
to = $(this).is('.prev') ? links.eq(links.size() - 1) : links.eq(0);
}
if(to.size()) {
to.click();
}
});
So, I found out what was wrong (Cheers Deng!), further down the code I had the following function (I had to add "link" into the remove caption code):
links.each(function(index) {
var link = $(this);
link.click(function(c) {
c.preventDefault();
if (hideScrollbars == "1") {
$('body').css({'overflow' : 'hidden'});
}
open(link.attr('href'));
links.filter('.selected').removeClass('selected');
link.addClass('selected');
var areThereAlts = $(".thumb", link).attr("alt"); //"link" needed to be added here
//alert(areThereAlts);
if (areThereAlts !== "") {
container.append('<div id="caption" style="display: block; font-family: Verdana; background-color: white; padding: 4px 5px 10px 5px; top -10px; width: 100%; height: 25px; vertical-align: middle; -moz-border-radius-topleft: 10px; -moz-border-radius-topright: 10px; color: #3f3f3f;"><font color="#3f3f3f">'+areThereAlts+'</font></div>') //caption
}
});
link.attr({'lb-position': index});
});
Related
I found this article that's supposed to be related to what I was looking for, which is sorting a list by class. However, in my code, it didn't work. So I'm trying to figure out how to solve the problem. I have two classes, "offline" and "none". I want the class "offline" to come at top and the class "none" to appear at bottom under "offline" area. I have one more class in each div's which is "indbox", therefore, I tried to use "getElementsByClassName" but it's not working.
Here's my code from codepen.
$(document).ready(function() {
$(".con-button").click(function(){
var cssObj = {};
cssObj.left = $(this).position().left;
cssObj.width = $(this).outerWidth();
$(".controls .effect").css( cssObj );
if(this.id == "c-all") {
$('.offline').hide();
$('.offline').fadeIn("slow").show();
$('.online').hide();
$('.online').fadeIn("slow").show();
$('.none').fadeIn("slow").show();
} else if (this.id == "c-online") {
$('.offline').hide();
$('.online').hide();
$('.online').fadeIn("slow").show();
$('.none').hide();
} else if (this.id == "c-offline") {
$('.offline').hide();
$('.offline').fadeIn("slow").show();
$('.online').hide();
$('.none').hide();
}
});
$(".con-button").eq(0).trigger("click");
getSteams();
var elem = $('#offline').find('div').sort(sortMe);
function sortMe(a, b) {
return a.getElementsByClassName("offline") < b.getElementsByClassName("none");
}
$('#offline').append(elem);
});
var channels = ["BasicallyIDoWrk", "FreeCodeCamp", "Golgothus", "OgamingSC2", "maatukka", "Vinesauce", "brunofin", "comster404", "esl_csgo"];
var cb = "?client_id=egn4k1eja0yterrcuu411n5e329rd3&callback=?";
function getSteams() {
channels.forEach(function(indchannel) {
//for (var channel in channels) {
//var indchannel = channel;
var streamURL = "https://api.twitch.tv/kraken/streams/" + indchannel + cb;
var channelURL = "https://api.twitch.tv/kraken/channels/" + indchannel + cb;
$.ajax({
url: streamURL,
type: 'GET',
dataType: "jsonp",
data: {
//action: 'query',
format: 'json',
},
headers: {
"Accept": "application/vnd.twitchtv.v5+json",
},
success: function(data) {
var game;
var status;
if(data.stream === null) {
$.getJSON(data._links.channel + "/?client_id=egn4k1eja0yterrcuu411n5e329rd3&callback=?", function(data2) {
if(data2.status == 404) {
game = "The Account doesn't exist";
status = "none";
} else {
game = "Offline";
status = "offline";
}
$("#offline").append('<div class="indbox ' + status + '"><a target="_blank" href="#">'+ indchannel + '<br/>' + game +'</a></div>');
} );
} else {
game = data.stream.game;
status = "online";
$("#online").append('<div class="indbox ' + status + '"><a target="_blank" href="#">'+ indchannel + '<br/>' + game +'</a></div>');
};
}
});
});
}
html, body{
height:100%;
margin: 0;
background-color: #ffffff;
}
.wrapper {
text-align: center;
position: relative;
width: 100%;
height: 100%;
display:block;
}
.container {
width: 75%;
margin: 30px auto 0;
position: relative;
}
.logobox img {
width: 20%;
margin: 0 auto;
}
.controls {
position: relative;
width: 100%;
}
.con-button {
position: relative;
background-color: white;
border: none;
margin: 0.5em 0 0 0;
padding: 0.5em 1em 0.5em 1em;
text-align: center;
color: rgb(100,65,164);
font-size: 20px;
transition: .4s;
}
.con-button:hover {
cursor: pointer;
/*border-bottom: 3px solid rgba(224, 217, 236, 1);*/
}
.con-button:focus {outline: 0;}
.divider hr {
border-top: 1px solid #6441A4;
}
.effect {
position: absolute;
display: block;
left: 0;
bottom: 5px;
height: 2px;
width: 60px;
transition: 0.4s ease-in-out;
/*border-bottom: 3px solid rgba(100, 65, 164, 1);*/
background: #6441A4;
}
.indbox {
width: 100%;
display: block;
margin: 5px 0px;
padding: 8px 0px;
}
.online {
background-color: #98FB98;
}
.offline {
background-color: #ff9999;
}
.none {
background-color: #D3D3D3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="container">
<div class="twitchtvarea">
<div class="logobox">
<img src="https://s6.postimg.org/bay7stotd/Twitch_Purple_RGB.png" />
</div>
<div class="twitchbox">
<div class="controls">
<button id="c-all" class="con-button active" type="button">All</button>
<button id="c-online" class="con-button" type="button">Online</button>
<button id="c-offline" class="con-button" type="button">Offline</button>
<div class="effect"></div>
</div>
<div class="divider"><hr></div>
<div id="online"></div>
<div id="offline"></div>
</div>
</div>
</div>
</div>
The code I would like for you to focus on is:
var elem = $('#offline').find('div').sort(sortMe);
function sortMe(a, b) {
return a.getElementsByClassName("offline") < b.getElementsByClassName("none");
}
$('#offline').append(elem);
Please help me fix it.
Looking through your code, I find out that you are using thisSort Function; however, your way of doing is incorrect. In the example, they have:
function compare(a, b) {
if (a is less than b by some ordering criterion) {
return -1;
}
if (a is greater than b by the ordering criterion) {
return 1;
}
// a must be equal to b
return 0;
}
So in order to sort "offline" before "none", your function has to return 1
function sortMe(a, b){
if (a.hasClass("offline")) {
return 1; //if an element has offline, move it above.
} else {
return -1; //if an element doesn't have offline, it means it's none. Move it down.
}
}
You might want to add in the condition to check whether they both have offline class.
Your problem can be solved by using the :
appendTo();
method.
instead of the :
append();
method.
I added two additional divs in your html code and made a small change to your javascript code ant it works !!!
the html goes like this :
<div class="divider"><hr></div>
<div id="online"></div>
<div id="offline">
<div class="notconnected"></div>
<div class="nonexisting"></div>
</div>
</div>
and the javascript was changed here :
if(data2.status == 404) {
game = "The Account doesn't exist";
status = "none";
}
else {
game = "Offline";
status = "offline";
}
if(status==="none"){
$('<div class="indbox ' + status + '" id="'+status+'"><a target="_blank" href="#">'+ indchannel + '<br/>' + game +'</a></div>').appendTo(".nonexisting");}
else{
$('<div class="indbox ' + status + '" id="'+status+'"><a target="_blank" href="#">'+ indchannel + '<br/>' + game +'</a></div>').appendTo(".notconnected");
}
} );
The Documentation for the method is here : appendTo()
In my project I'm using jqPagination plugin. I really like the functionality, but I was wondering if it's possible to customize it in the way that max-page number always appears outside of the input box. Here is my link to the jsfiddle https://jsfiddle.net/webIra7/hqz90Lwj/1/
<div class="some-container">
<div class="loaded-page">First page </div>
<div class="loaded-page">Second page</div>
<div class="loaded-page">Third page</div>
</div>
<div class="gigantic pagination">
‹
<input class="pagenumber" type="text" readonly="readonly" />
›
</div>
You can access to plugin properties like this:
($('.pagination').jqPagination('option', 'max_page'))
Check the fiddle to see it working: https://jsfiddle.net/ivan0013/hqz90Lwj/5/
According to the customization section of the documentation for the jqPagination plugin, you can pass a page_string to the options. The default value is 'Page {current_page} of {max_page}'.
You could change the page_string in the options to be just 'Page {current_page}', then put the max page number in a separate HTML element outside of the pagination element.
See updated fiddle here.
You can calculate the maxPageNumber outside the jqPagination object and set this value to a span element after the next button.
To change the page format string you can use:
page_string: 'Page {current_page}',
Do not copy or include the src code of plugin, you may include it with:
<script src="https://rawgit.com/beneverard/jqPagination/master/js/jquery.jqpagination.min.js"></script>
The snippet:
$(document).ready(function () {
// hide all but the first of our paragraphs
$('.some-container div.loaded-page:not(:first)').hide();
// compute the maxPageNumber
var maxPageNumber = $('.some-container div.loaded-page').length;
// set this value as you wish:
$('#maxPageNumber').text(maxPageNumber);
// initialize the jqPagination
$('.pagination').jqPagination({
max_page: maxPageNumber,
page_string: 'Page {current_page}', // change the string format
paged: function (page) {
// a new 'page' has been requested
// hide all paragraphs
$('.some-container div.loaded-page').hide();
// but show the one we want
$($('.some-container div.loaded-page')[page - 1]).show();
}
});
});
.pagenumber::-ms-clear {
width: 0;
height: 0;
}
.pagination {
display: inline-block;
border-radius: 3px;
}
.pagination a {
display: block;
float: left;
width: 20px;
height: 20px;
outline: none;
border-right: 1px solid #CDCDCD;
border-left: 1px solid #CDCDCD;
color: #555555;
vertical-align: middle;
text-align: center;
text-decoration: none;
font-size: 15px;
font-family: Helvetica, Arial, sans-serif;
/* ATTN: need a better font stack */
background-color: #f3f3f3;
}
.pagination a:hover, .pagination a:focus, .pagination a:active {
background-color: #006699;
color: white;
border: 1px solid #cdcdcd;
}
.pagination a.previous:hover, .pagination a.previous:focus, .pagination a.previous:active, .pagination a.next:hover,
.pagination a.next:focus, .pagination a.next:active, .pagination a.disabled, .pagination a.disabled:hover,
.pagination a.disabled:focus, .pagination a.disabled:active {
background-color: #006699;
color: #A8A8A8;
cursor: default;
color: white;
}
.pagination a:first-child {
border: none;
border-radius: 2px 0 0 2px;
}
.pagination a:last-child {
border: none;
border-radius: 0 2px 2px 0;
}
.pagination input {
float: left;
margin: 0;
padding: 0;
width: 115px;
height: 20px;
outline: none;
border: none;
vertical-align: middle;
text-align: center;
}
/* gigantic class for demo purposes */
.gigantic.pagination {
margin: 0;
}
.gigantic.pagination a {
font-size: 30px;
background-color: #eee;
border-radius: 0;
color: #006699;
float: left;
height: 35px;
width: 35px;
line-height: 30px;
border: solid 1px #ccc;
}
.gigantic.pagination input {
width: 120px;
font-size: 15px;
font-family: Helvetica, Arial, sans-serif;
margin: 0;
padding: 7px 0;
}
/* log element for demo purposes */
.log {
display: none;
background-color: #EDEDED;
height: 300px;
width: 524px;
overflow: auto;
margin-left: 0;
list-style: none;
padding: 10px;
}
.log li {
margin-top: 0;
margin-bottom: 5px;
}
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://rawgit.com/beneverard/jqPagination/master/js/jquery.jqpagination.min.js"></script>
<div class="some-container">
<div class="loaded-page">First page </div>
<div class="loaded-page">Second page</div>
<div class="loaded-page">Third page</div>
</div>
<div class="gigantic pagination">
‹
<input class="pagenumber" type="text" readonly="readonly" />
›
<span id="maxPageNumber" style='margin-top: 1.00em;margin-left:1.25em; display:inline-block;'/>
</div>
HTML:
<div class="some-container">
<div class="loaded-page">First page </div>
<div class="loaded-page">Second page</div>
<div class="loaded-page">Third page</div>
</div>
<div class="gigantic pagination">
‹
<input class="pagenumber" type="text" readonly="readonly" />
›
<input class="maxPageNumber" type="text" readonly="readonly" id="maxPag" />
</div>
JS:
(function(e) {
"use strict";
e.jqPagination = function(t, n) {
var r = this;
r.$el = e(t);
r.el = t;
r.$input = r.$el.find(".pagenumber");
r.$el.data("jqPagination", r);
r.init = function() {
r.options = e.extend({}, e.jqPagination.defaultOptions, n);
r.options.max_page === null && (r.$input.data("max-page") !== undefined ? r.options.max_page = r.$input.data("max-page") : r.options.max_page = 1);
r.$input.data("current-page") !== undefined && r.isNumber(r.$input.data("current-page")) && (r.options.current_page = r.$input.data("current-page"));
r.$input.removeAttr("readonly");
r.updateInput(!0);
r.$input.on("focus.jqPagination mouseup.jqPagination", function(t) {
if (t.type === "focus") {
var n = parseInt(r.options.current_page, 10);
e(this).val(n).select()
}
if (t.type === "mouseup") return !1
});
r.$input.on("blur.jqPagination keydown.jqPagination", function(t) {
var n = e(this),
i = parseInt(r.options.current_page, 10);
if (t.keyCode === 27) {
n.val(i);
n.blur()
}
t.keyCode === 13 && n.blur();
t.type === "blur" && r.setPage(n.val())
});
r.$el.on("click.jqPagination", "a", function(t) {
var n = e(this);
if (n.hasClass("disabled")) return !1;
if (!t.metaKey && !t.ctrlKey) {
t.preventDefault();
r.setPage(n.data("action"))
}
})
};
r.setPage = function(e, t) {
if (e === undefined) return r.options.current_page;
var n = parseInt(r.options.current_page, 10),
i = parseInt(r.options.max_page, 10);
if (isNaN(parseInt(e, 10))) switch (e) {
case "first":
e = 1;
break;
case "prev":
case "previous":
e = n - 1;
break;
case "next":
e = n + 1;
break;
case "last":
e = i
}
e = parseInt(e, 10);
if (isNaN(e) || e < 1 || e > i) {
r.setInputValue(n);
return !1
}
r.options.current_page = e;
r.$input.data("current-page", e);
r.updateInput(t)
};
r.setMaxPage = function(e, t) {
if (e === undefined) return r.options.max_page;
if (!r.isNumber(e)) {
console.error("jqPagination: max_page is not a number");
return !1
}
if (e < r.options.current_page) {
console.error("jqPagination: max_page lower than current_page");
return !1
}
r.options.max_page = e;
r.$input.data("max-page", e);
r.updateInput(t)
};
r.updateInput = function(e) {
var t = parseInt(r.options.current_page, 10);
r.setInputValue(t);
r.setLinks(t);
e !== !0 && r.options.paged(t)
};
r.setInputValue = function(e) {
var t = r.options.page_string,
n = r.options.max_page;
t = t.replace("{current_page}", e).replace("{max_page}", n);
r.$input.val(t);
$("#maxPag").val("of " + n);
};
r.isNumber = function(e) {
return !isNaN(parseFloat(e)) && isFinite(e)
};
r.setLinks = function(e) {
var t = r.options.link_string,
n = parseInt(r.options.current_page, 10),
i = parseInt(r.options.max_page, 10);
if (t !== "") {
var s = n - 1;
s < 1 && (s = 1);
var o = n + 1;
o > i && (o = i);
r.$el.find("a.first").attr("href", t.replace("{page_number}", "1"));
r.$el.find("a.prev, a.previous").attr("href", t.replace("{page_number}", s));
r.$el.find("a.next").attr("href", t.replace("{page_number}", o));
r.$el.find("a.last").attr("href", t.replace("{page_number}", i))
}
r.$el.find("a").removeClass("disabled");
n === i && r.$el.find(".next, .last").addClass("disabled");
n === 1 && r.$el.find(".previous, .first").addClass("disabled")
};
r.callMethod = function(t, n, i) {
switch (t.toLowerCase()) {
case "option":
if (i === undefined && typeof n != "object") return r.options[n];
var s = {
trigger: !0
},
o = !1;
e.isPlainObject(n) && !i ? e.extend(s, n) : s[n] = i;
var u = s.trigger === !1;
s.current_page !== undefined && (o = r.setPage(s.current_page, u));
s.max_page !== undefined && (o = r.setMaxPage(s.max_page, u));
o === !1 && console.error("jqPagination: cannot get / set option " + n);
return o;
case "destroy":
r.$el.off(".jqPagination").find("*").off(".jqPagination");
break;
default:
console.error('jqPagination: method "' + t + '" does not exist');
return !1
}
};
r.init()
};
e.jqPagination.defaultOptions = {
current_page: 1,
link_string: "",
max_page: null,
page_string: "Page {current_page}",
page_string2: "of {max_page}",
paged: function() {}
};
e.fn.jqPagination = function() {
var t = this,
n = e(t),
r = Array.prototype.slice.call(arguments),
i = !1;
if (typeof r[0] == "string") {
r[2] === undefined ? i = n.first().data("jqPagination").callMethod(r[0], r[1]) : n.each(function() {
i = e(this).data("jqPagination").callMethod(r[0], r[1], r[2]);
});
return i
}
t.each(function() {
new e.jqPagination(this, r[0])
})
}
})(jQuery);
if (!console) {
var console = {},
func = function() {
return !1
};
console.log = func;
console.info = func;
console.warn = func;
console.error = func
};
$(document).ready(function() {
// hide all but the first of our paragraphs
$('.some-container div.loaded-page:not(:first)').hide();
$('.pagination').jqPagination({
max_page : $('.some-container div.loaded-page').length,
paged : function(page) {
// a new 'page' has been requested
// hide all paragraphs
$('.some-container div.loaded-page').hide();
// but show the one we want
$($('.some-container div.loaded-page')[page - 1]).show();
}
});
$('.pagination2').jqPagination({
max_page : $('.some-container div.loaded-page').length,
paged : function(page) {
// a new 'page' has been requested
// hide all paragraphs
$('.some-container div.loaded-page').hide();
// but show the one we want
$($('.some-container div.loaded-page')[page - 1]).show();
}
});
});
CSS:
.pagenumber::-ms-clear{
width: 0;
height: 0;
}
.pagination{
display: inline-block;
border-radius: 3px;
}
I include <input class="maxPageNumber" type="text" readonly="readonly" id="maxPag" /> change page_string: "Page {current_page} of {max_page}" to page_string: "Page {current_page}", page_string2: "of {max_page}" and include $("#maxPag").val("of" + n);
How do I change the placeholder like as the elements replace each other place.
Please see the example
https://jsfiddle.net/98h31o9v/11/
JavaScript
indexOfCell = 0;
add boxes to #div element
$('#add_box').on('click', function() {
var cell = $("<div></div>");
var elementObj = cell.get(0);
$('#div').append(elementObj);
cell.addClass('content-box').attr('id', 'box_' + indexOfCell);
cell.text(indexOfCell);
indexOfCell += 1;
console.log(elementObj);
$(cell).draggable({
helper: 'original',
zIndex: 10001,
start: function(event, ui) {
if ($(this).data('placeholder') === undefined) {
$(this).data('placeholder', createPlaceholder($(this)));
}
setPlaceHolder($(this).data('placeholder'), $(this));
$(this).after($(this).data('placeholder'));
},
stop: function(event, ui) {
$(this).css('left', $(this).data('placeholder').css('left'));
$(this).css('top', $(this).data('placeholder').css('top'));
$(this).data('placeholder').after($(this));
$(this).data('placeholder').detach();
}
});
$(cell).droppable({
tolerance: 'intersect',
greedy: true,
over: function(event, ui) {
replaceTwoItem(ui.draggable.data('placeholder'), $(this));
}
});
create placeholder
function createPlaceholder(that) {
var className = that.attr('class');
var placeholder = $(document.createElement(that.get(0).nodeName))
.addClass(className || className + " ui-sortable-placeholder")
.removeClass("ui-sortable-helper").css({
background: 'yellow',
border: '1px solid grey'
});
return placeholder;
}
set the placeholder to cell
function setPlaceHolder(placeholder, cell) {
placeholder.css('width', cell.width());
placeholder.css('height', cell.height());
placeholder.css("display", 'block');
placeholder.css('position', 'absolute');
placeholder.css('top', cell.css('top'));
placeholder.css('left', cell.css('left'));
}
replace two item when drag
function replaceTwoItem(itemFrom, itemTo) {
var itemToInsert;
var action;
if (itemFrom.index() === 0) {
itemToInsert = itemFrom.parent();
action = "prepend";
} else {
itemToInsert = itemFrom.prev();
action = "after";
}
itemTo.before(itemFrom);
if (itemTo.get(0) != itemToInsert.get(0)) {
if (action == 'prepend') {
itemToInsert.prepend(itemTo);
} else if (action == 'after') {
itemToInsert.after(itemTo);
}
}
}
});
HTML
<button id="add_box">AddBox</button>
<div id="div">
</div>
CSS
.content-box {
width: 100px;
height: 100px;
background: green;
margin: 5px;
float: left;
}
After the brief discussion in the comments about your requirements I think you can get rid of most of the code you're currently using. The example on the jquery
ui website can be tweaked slightly to get what you want.
Fiddle Example
HTML:
<button id="add_box">AddBox</button>
<div id="sortable" class="ui-sortable">
</div>
JQuery:
$('#add_box').on('click', function() {
//Determine the existing child count.
var boxCount = $('#sortable').children().length;
//Create a new "box" and add it to the end of the list.
var newBox = $('<div class="ui-state-default">' + boxCount + '</div>');
$('#sortable').append(newBox);
//Invoke the sortable function to ensure the appropriate events are bound.
$("#sortable").sortable({
placeholder: "ui-state-highlight"
});
});
CSS:
The below can be cleaned up somewhat.
#sortable {
margin: 0;
padding: 0;
}
.ui-state-highlight {
background: yellow;
margin: 0 5px 5px 5px;
color: black;
float: left;
width: 100px;
height: 100px;
}
.ui-state-default {
background: green;
margin: 0 5px 5px 5px;
color: black;
float: left;
width: 100px;
height: 100px;
}
Update .ui-state-default to change the initial colour and update .ui-state-highlight to change the placeholder colour.
I've made a simple jQuery script which stores values "voted1", "voted2", "voted3" in localStorage. The problem is that on click it stores all values at the same time, and I need it per click as it should be later called (e.g. if "value3" exists begin jQuery logic...)
I can't figure this out, after weeks of testing..
HTML:
[gallery link="none" size="medium" ids="102,13,27,25,23,15" orderby="rand"]
<div class="exists" style="display: none;">Thank you for voting!</div>
CSS:
.gallery-item a {
background-color: black;
border: 1px solid orange;
border-radius: 6px;
color: orange;
display: inline-table;
font-size: 14px;
font-weight: bold;
max-width: 100%;
width: 32%;
}
.exists {
background-color: black;
border-radius: 18px;
box-shadow: 1px 3px 20px -3px grey inset;
display: block;
height: 32%;
left: 24%;
margin-left: 10%;
margin-right: 10%;
margin-top: 10%;
max-width: 100%;
padding-left: 12%;
padding-top: 6%;
position: fixed;
top: 23%;
width: 36%;
z-index: 999999;
color: olivedrab;
font-weight: bold;
cursor: context-menu;
}
.voted {
background-color: green !important;
}
jQuery:
$(document).ready(function() {
var voteLink = $('.gallery-item a');
var votedYes = $('.exists');
voteLink.one('click', function() {
// localStorage.setItem('voted1', 'yes1');
$(this).text('Thank you!');
$(this).addClass('voted');
})
voteLink.one('click', function() {
// localStorage.setItem('voted2', 'yes2');
$(this).text('Thank you!');
$(this).addClass('voted');
})
voteLink.one('click', function() {
localStorage.setItem('voted3', 'yes3');
$(this).text('Thank you!');
$(this).addClass('voted');
if($('.voted').length === 3){
voteLink.fadeOut('slow');
$('.exists').fadeIn(1800);
}
if (localStorage.getItem("voted3")) {
voteLink.remove();
votedYes.fadeIn(1800);
}
});
As I said, on first click it places all values in localStorage and I need this separated.
Thanks guys.
$(document).ready(function() {
var voteLink = $(".gallery-item a");
var votedYes = $(".exists");
if (localStorage.getItem("count") === null) {
localStorage.setItem("count", 1)
}
if (!(localStorage.getItem("voted3") === "yes3")) {
var i = Number(localStorage.getItem("count")),
fn = function(e) {
if (i < 3) {
localStorage.setItem("voted" + i, "yes" + i);
$(this).text("Thank you! for vote " + i)
.addClass("voted" + i);
localStorage.setItem("count", 1 + i);
i = Number(localStorage.getItem("count"));
} else {
localStorage.setItem("voted" + i, "yes" + i);
$(this).text("Thank you! for vote " + i)
.addClass("voted" + i)
.fadeOut("slow");
if (localStorage.getItem("voted3") === "yes3") {
voteLink.remove();
votedYes.fadeIn(1800);
}
}
};
voteLink.on("click", fn);
} else {
// if `localStorage` has property `"voted3"` and value equals `"yes3"`,
// do stuff
}
})
Caveat: This answer may be completely off, since your question comes without all the details of your use case. However ...
The following code assumes that ...
up to 3 votes shall be recorded in localStorage
in order to cast the vote n+1, vote n must have been recorded before.
Either register the handlers contingent on the content in localStorage:
if (
localStorage.getItem("voted1")
&& !localStorage.getItem("voted2")
) {
voteLink.one('click', function() {
localStorage.setItem('voted2', 'yes2');
//...
});
}
... or test the localStorage contents inside your event handler:
fn_vote2 = function() {
if (
localStorage.getItem("voted1")
&& !localStorage.getItem("voted2")
) {
localStorage.setItem('voted2', 'yes2');
//...
voteLink.off('click', fn_vote2);
}
};
voteLink.on('click', fn_vote2);
The generalization for vote1, vote3 should come easy. Note that the latter solution implies that you register the handler not just for a single event. Instead you deregister it upon success.
The advantage of the method is the option for cascaded voting without reloading the page.
Btw, since localStorage persists over sessions, it is advisable not to use generic keys like vote<n>.
The following code displays as intended in FireFox, but isn't displaying at all in Internet Explorer (v8).
// getLimits init
Frog.API.get('users.getInfo',
{
'params': {'id': UWA.Environment.user.id, 'details':'groups' },
'onSuccess': AssignPoints.getLimit,
'onError': function(err) { alert(err); }
});
...
// work out the user's limit, and how many points they've spent this week
// use LEAP library if necessary
AssignPoints.getLimit = function(data) {
for (var i in data[0].groups) {
if (data[0].groups[i].name.indexOf("LEAP") != -1) {
AssignPoints.Limit = data[0].groups[i].name.substr(5,3);
}
}
/************** IT'S THIS LINE ONWARDS WHERE THE ALERTS SEEM TO BREAK IN IE */
if (AssignPoints.Limit == 0) {
AssignPoints.Specialist = true;
}
UWA.Data.getJson(AssignPoints.URL + "?cmd=getLimitsAndTotals&Giver_ID=" + AssignPoints.CurrentUser, AssignPoints.getPointsSpent);
}
AssignPoints.getPointsSpent = function(data) {
AssignPoints.SpentWeekly = data.SpentWeekly;
AssignPoints.SpentTotal = data.SpentTotal;
AssignPoints.displayLimitAndTotals();
}
// display data from getLimitAndTotals
AssignPoints.displayLimitAndTotals = function() {
var LimitsAndTotalsHTML = '<h2>Points Allocation</h2>';
if (AssignPoints.Specialist == false) {
LimitsAndTotalsHTML += '<ul><li>Weekly Limit: <strong>' + AssignPoints.Limit + '</strong></li>';
} else {
LimitsAndTotalsHTML += '<ul><li>Weekly Limit: <strong>Unlimited</strong></li>';
}
LimitsAndTotalsHTML += '<li>Spent this week: <strong style="color:#990000;">' + AssignPoints.SpentWeekly + '</strong></li>' +
'<li>Spent total: <strong>' + AssignPoints.SpentTotal + '</strong></li></ul>';
$('div#limits').html(LimitsAndTotalsHTML);
}
EDIT: CSS & HTML
I don't think it's a CSS/HTML issue, as I have the previous version of this script (which I decided to rewrite because it was hideous code and some odd mash-up of procedural and just pure bodging) which displays correctly in IE using exactly the same HTML&CSS.
#total_container
{ overflow: hidden; width: 870px; }
#groups
{ width: 250px; float: left; padding: 10px; }
#right_container
{ width: 580px; float: left; padding: 10px; }
span.check
{ font-size: 10px; color: #666; }
span.err
{ color: red; font-weight: 700; }
#limits, #search_div
{ width: 270px; float:left; padding: 0 10px; }
#groups li, #groups ul
{ list-style-type: none; background: none; margin: 0; padding: 0; }
#groups li a
{ background-color: #999; color: #eee; display: block; margin: 5px 0; border: #666; padding: 8px 2px 8px 10px; width: 243px; }
#groups li a:hover
{ background-color: #990000; }
The HTML is just <div id="limits"></div> and the JS updates it.
// EDIT
SECOND EDIT: ALERTS
I've tried putting random alerts into the code. In IE, in the for (var i in data[0].groups) loop, the alerts work. If I place an alert at any point after that for loop, the alert doesn't appear at all, regardless of whether I use a variable name or a random string such as "test".
In FF, the alerts work regardless of placement within either function.
** // SECOND EDIT **
FireFox, working as intended
Internet Explorer, b0rked
Does anyone know what might be breaking IE?
Thanks in advance.
OK! I've found the problem.
IE didn't like this segment of code:
for (var i in data[0].groups) {
if (data[0].groups[i].name.indexOf("LEAP") != -1) {
AssignPoints.Limit = data[0].groups[i].name.substr(5,3);
}
}
When I've changed that to this format:
for (var i = 0; i < data[0].groups.length; i++) {
if (data[0].groups[i].name.substr(0,4) == "LEAP") {
AssignPoints.Limit = data[0].groups[i].name.substr(5,3);
}
}
It works as intended in FF and IE.