jQuery UI Sortable - Load Positions - javascript

I am using this code to save the position of the sorted div's with jquery-ui.
The code works great but my question is...how can I load them again into position once saved?
Here's the code I'm using to save to positions:
<div id="sortable">
<div id="2000"></div>
<div id="1000"></div>
<div id="3000"></div>
</div>
$('#sortable').sortable({
update: function () { save_new_order() }
});
function save_new_order() {
var a = [];
$('#sortable').children().each(function (i) {
a.push($(this).attr('id') + ':' + i);
});
var s = a.join(',');
alert(s);
localStorage.setItem("positions", s);
}
How can I load?

You can retrieve the value and update the order as shown below. Note that I'm using the built in toArray method to retrieve the order:
$(function() {
var $sortable = $('#sortable');
var positions = JSON.parse(localStorage.getItem('positions'));
if (positions) {
$.each(positions, function(i, position) {
var $target = $sortable.find('#' + position);
$target.appendTo($sortable); // or prependTo for reverse
});
}
$sortable.sortable({
update: saveNewOrder
});
function saveNewOrder() {
var positions = JSON.stringify($sortable.sortable("toArray"));
localStorage.setItem('positions', positions);
}
});
JSFiddle demo

Related

jQuery function does not work on mouseover and click state

Building a new site and trying to reuse a JavaScript from the current site that change image on hover. I have a hard time to understand JavaScript so I hope someone can help me to see what I'm missing or doing wrong.
The current site (where I copied from) has many more script running and I don't know if some other script is missing. I have tried to change the initializing part of the script to fit the new site. Please have a look at the puzzlepiece on the current page. http://www.collyfiltreringsteknik.se.
I have got the script running to a point where it adds the four "quad" divs but the mouseover and click function does not work.
This is the html code
<div id="companyvalues" class="clearfix">
<div class="valueimage"></div>
</div>
The jQuery part
(function($){
$.fn.extend({
companyvalues: function(kwargs) {
var defaults = {
static_base:''
};
var options = $.extend(defaults, kwargs);
return this.each(function() {
var obj = $(this);
var div = $('div', obj);
var topleft = $('<div class="quad topleft" data-image="i0000" data-href="/grundpelare/tillganglighet/"></div>');
var topright = $('<div class="quad topright" data-image="i0003" data-href="/grundpelare/konkurrenskraft/"></div>');
var bottomleft = $('<div class="quad bottomleft" data-image="i0002" data-href="/grundpelare/miljoforbattring/"></div>');
var bottomright = $('<div class="quad bottomright" data-image="i0001" data-href="/grundpelare/kostnadsreducering/"></div>');
obj.prepend(bottomright);
obj.prepend(bottomleft);
obj.prepend(topright);
obj.prepend(topleft);
var divs = $('div.quad', obj);
$([ '/uploads/pages/varden_0000_yellow.png',
'/uploads/pages/varden_0001_red.png',
'/uploads/pages/varden_0002_green.png',
'/uploads/pages/varden_0003_blue.png'
]).preload({base_url:options.static_base});
divs.mouseover(function(event) {
var item = $(this);
var data_image = item.attr('data-image');
div.addClass(data_image);
event.preventDefault();
event.stopPropagation();
});
divs.mouseout(function(event) {
var item = $(this);
div.removeClass('i0000');
div.removeClass('i0001');
div.removeClass('i0002');
div.removeClass('i0003');
event.preventDefault();
event.stopPropagation();
});
divs.click(function(event) {
var item = $(this);
var href = item.attr('data-href')
document.location.href=href;
event.preventDefault();
event.stopPropagation();
});
});
}
});
})(jQuery);
Initializing the script.
$(document).ready(function() {
$('#companyvalues').companyvalues();
});

jquery cannot get div to show using this selector

I am querying the Twitch API for a list of users in my database, to see if they are online.
I am essentially listing them all, with "display: none" and then unhiding if online:
$('.online_list').each(function (index) {
var tnick = $(this).data('tnick');
$.getJSON("https://api.twitch.tv/kraken/streams?client_id={:twitch_key}&channel="+tnick+"", function(a) {
if (a["streams"].length > 0)
{
alert(tnick);
$(this).show();
console.log(index + ": " + $( this ).text());
}
});
});
In my testing, the alert(tnick) works perfectly, so I know it's running. The problem is $(this).show(); just isn't working.
Here's example HTML:
<div class="online_list" data-tnick="test" style="display: none;">test:Twitch <span>(Online)</span></div>
<div class="online_list" data-tnick="test2" style="display: none;">test2:Twitch <span>(Online)</span></div>
this is the current scope object!
to fix your code you can do the following:
$('.online_list').each(function (index) {
var $that = $(this); // create a temp var that
var tnick = $that.data('tnick');
$.getJSON("https://api.twitch.tv/kraken/streams?client_id={:twitch_key}&channel="+tnick+"", function(a) {
if (a && a["streams"] && a["streams"].length > 0) {
alert(tnick);
$that.show(); // use that instead of this
console.log(index + ": " + $that.text());
}
});
});
Check out this resource for more information on scope & this: http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/
EDIT:
Also, like #djxak suggests, you can use the element parameter of the callback, that is more simple and clean in my opinion.
The #djxak suggests:
$('.online_list').each(function (index, element) {
//... (scope1 code)
$.getJSON("", function(a) {
//... (scope2 code)
$(element).show();
});
});
My approach:
$('.online_list').each(function (index) {
//... (scope1 code)
var $current = $(this);
$.getJSON("", function(a) {
//... (scope2 code)
$current.show();
});
});
Info about each function and element parameter in jQuery docs: https://api.jquery.com/each/#each-function

Jquery Loading news listings into dom

I want simply to load/display my top 500 news into my DOM.
I'm not sure why doesn't display it on my <div id="hackernewsrss" ></div>
And if there's any other better way to display this? or to code it? Perhaps I can learn.
var LoadNews = $("#hackernewsrss");
LoadNews.load(function(event) {
parseTopStories('https://hacker-news.firebaseio.com/v0/topstories', '#hackernewsrss');
});
function parseTopStories(url, container) {
var hackernewsAPI = "https://hacker-news.firebaseio.com/v0/topstories.json";
$.getJSON(hackernewsAPI, function(json) {
var requests = [];
for (var i = 0; i < 10; i++) {
requests.push($.getJSON('https://hacker-news.firebaseio.com/v0/item/' + json[i] + '.json'));
}
$.when.apply($, requests)
.done(function() {
var results = []
.slice.call(arguments);
var list = results.map(function(arr) {
var thetemplate = '<li>' + arr[0].title + '</li>';
return thetemplate;
});
$(container).html('<ol>' + list.join('') + '</ol>');
console.log(container); //logs #hackernewsrss
});
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hackernewsrss"></div>
Can anyone help please?
If you try:
$(function(){
parseTopStories('https://hacker-news.firebaseio.com/v0/topstories', '#hackernewsrss');
});
All goes well.
I am not sure why you have load event attached to the div. It is usually used to trigger when image is loaded or window:
JQuery reference

getElementsByTagName('img').length logs out to 0

I have read multiple posts on this, but still don't understand why document.getElemenstsByTagName('img').length prints out '0' but when you console log it shows you the right length.
To further explain my problem, part of my HTML looks like this
<div id="parent">
<div id="slider">
</div>
</div>
Now i am dynamically adding the elements as children to the #slider element.
In my javascript i have an object
var manualSlide = {
imageLength: document.getElementsByTagName('img').length,
//other properties
};
Why does the property 'imageLength' gets assigned '0' instead of the actual length?
Edit:
Here is my entire script
<script>
$.getJSON('data.json',function(data){
$.each(data.images, function(key){
setImages(data.images[key]);
});
});
function setImages(obj){
var imgTag = '';
imgTag += "<img src='" + obj.Url + "' style='width:800px;height:400px' alt ='"+ obj.Title +"' name='pics'/>";
$('#slider').append(imgTag);
}
$(document).ready(function(){
var slide = getManualSlide();
document.getElementsByClassName('left').onclick = function(){
slide.previousImg();
};
document.getElementsByClassName('right')[0].onclick = function(){
slide.nextImg();
};
function getManualSlide(){
var manualSlide = {
imageNum : 1,
imageLength: document.getElementsByTagName('img').length,
image: document.getElementsByTagName('img'),
previousImg: function(){
if(this.imageNum > 1){
this.imageNum --;
}
else{
this.imageNum = this.imageLength;
}
document.pics.src = this.image[this.imageLength - 1];
},
nextImg: function(){
if(this.imageNum > this.imageNum){
this.imageNum ++;
}
else{
this.imageNum = 1;
}
console.log(document.getElementsByTagName('img').length);
console.log(this.imageLength);
document.pics.src = this.image[this.imageLength - 1];
}
};
return manualSlide;
}
});
</script>
It's all about where or when your code gets executed.
You have to make sure your code gets executed after the image tags are parsed (added to the DOM tree).
To do that you could put your code either behind the img-tags in the body or you wait for the document to be loaded:
<script>
document.addEventListener("DOMContentLoaded", function(event) {
imageLength = document.getElementsByTagName('img').length;
console.log(imageLength);
});
</script>
You can read more about this event here.
If you are using jQuery you could also use
$(document).ready(function(){ /* your code goes here */ });
which does exactly the same.
Because the object was created when no img tags were in the document. The object data will not update with the document. If you want this behavior you should use events.
Instead create a function to return an updated object. See below:
function getManualSlide()
{
var imgLen = document.getElementsByTagName('img').length;
var manualSlide = {
imageLength: imgLen
};
return manualSlide;
}
http://jsfiddle.net/2akca0dg/2/

jQuery dictionary alphabet filter to SharePoint list

I have a list in SP2013 which I am pulling the list items using Javascript on a publishing page. I need to apply alphabetic filtering to this list, but the filter doesn't functioning on this list; however, the filter works perfectly on plain static text. Here is my code to pull the list items:
$(function () {
if (glossaryQuery && glossaryQuery.Rows) {
var liGlossaryHTML = [];
$('#glossary_list').toggle();
$.each(glossaryQuery.Rows, function (index, r) {
liGlossaryHTML.push('<li><strong>' + r.Title + '</strong><br/>' + r.Definition + '</li>');
});
$('#glossary_list ul').html(liGlossaryHTML.join(''));
}
});
and here is the filter:
var triggers = $('ul.alphabet li a');
var filters = $('#glossary_list ul li');
triggers.click(function() {
var takeLetter = $(this).text(), result = 0;
filters.parent().hide();
filters.each(function(i) {
if ( RegExp('^'+takeLetter).test($(this).text()) ) {
result += 1;
$(this).parent().fadeIn(222);
}
});
});
and the HTML:
<div id="glossary_list" style="display:none;">
<ul></ul>
</div>
Any help is so appreciated.
My suspicion is that because you're adding the list items after page load that filters doesn't actually match anything at the time that it is run. I suggest moving the assignment inside the click handler. There are some other improvements you could make to make it more efficient/readable as well.
$('ul.alphabet li a').click(function() {
var takeLetter = $(this).text(),
result = 0
expr = new RegExp('^' + takeLetter);
var filters = $('#glossary_list ul li')
.parent()
.hide();
filters.each(function(i) {
var $filter = $(this);
if (expr.test($filter.text())) {
result += 1;
$filter.parent().fadeIn(222);
}
});
});

Categories

Resources