I'm having some issues implementing this template into my MVC application.
https://bootsnipp.com/snippets/featured/pinterest-like-responsive-grid
My CSS and code works fine, but the Javascript doesn't work.
I'm using a partial view to contain the code which looks like this:
#model List<Assignment_3.Models.Word>
<script type="text/javascript" src='#Url.Content("~/Scripts/ResponsiveGrid.js")'></script>
<div class="container">
<div class="row">
<div>
<section id="pinBoot">
#foreach (var word in Model)
{
<ItemTemplate>
<article class="white-panel">
<a href="#Url.Action("Detail", new { id = Word.WordId })">
<img src="#Url.Content(Idiom.Imagepath)" />
</a>
<h4 class="textwrapper">Test</h4>
<p>Language</p>
</article>
</ItemTemplate>
}
</section>
</div>
</div>
</div>
<style>
body {
background-color: #eee;
}
.textwrapper {
word-break: break-all;
}
#pinBoot {
position: relative;
max-width: 100%;
width: 100%;
}
img {
max-width: 100%;
height: auto;
}
.white-panel {
position: absolute;
background: white;
box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.3);
padding: 10px;
}
.white-panel h1 {
font-size: 1em;
}
.white-panel h1 a {
color: #A92733;
}
.white-panel:hover {
box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.5);
margin-top: -5px;
-webkit-transition: all 0.3s ease-in-out;
-moz-transition: all 0.3s ease-in-out;
-o-transition: all 0.3s ease-in-out;
transition: all 0.3s ease-in-out;
}
</style>
Here is the Javascript file:
$(document).ready(function () {
$('#pinBoot').pinterest_grid({
no_columns: 4,
padding_x: 10,
padding_y: 10,
margin_bottom: 50,
single_column_breakpoint: 700
});
});
usage:
$(document).ready(function () {
$('#blog-landing').pinterest_grid({
no_columns: 4
});
});
; (function ($, window, document, undefined) {
var pluginName = 'pinterest_grid',
defaults = {
padding_x: 10,
padding_y: 10,
no_columns: 3,
margin_bottom: 50,
single_column_breakpoint: 700
},
columns,
$article,
article_width;
function Plugin(element, options) {
this.element = element;
this.options = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype.init = function () {
var self = this,
resize_finish;
$(window).resize(function () {
clearTimeout(resize_finish);
resize_finish = setTimeout(function () {
self.make_layout_change(self);
}, 11);
});
self.make_layout_change(self);
setTimeout(function () {
$(window).resize();
}, 500);
};
Plugin.prototype.calculate = function (single_column_mode) {
var self = this,
tallest = 0,
row = 0,
$container = $(this.element),
container_width = $container.width();
$article = $(this.element).children();
if (single_column_mode === true) {
article_width = $container.width() - self.options.padding_x;
} else {
article_width = ($container.width() - self.options.padding_x *
self.options.no_columns) / self.options.no_columns;
}
$article.each(function () {
$(this).css('width', article_width);
});
columns = self.options.no_columns;
$article.each(function (index) {
var current_column,
left_out = 0,
top = 0,
$this = $(this),
prevAll = $this.prevAll(),
tallest = 0;
if (single_column_mode === false) {
current_column = (index % columns);
} else {
current_column = 0;
}
for (var t = 0; t < columns; t++) {
$this.removeClass('c' + t);
}
if (index % columns === 0) {
row++;
}
$this.addClass('c' + current_column);
$this.addClass('r' + row);
prevAll.each(function (index) {
if ($(this).hasClass('c' + current_column)) {
top += $(this).outerHeight() + self.options.padding_y;
}
});
if (single_column_mode === true) {
left_out = 0;
} else {
left_out = (index % columns) * (article_width +
self.options.padding_x);
}
$this.css({
'left': left_out,
'top': top
});
});
this.tallest($container);
$(window).resize();
};
Plugin.prototype.tallest = function (_container) {
var column_heights = [],
largest = 0;
for (var z = 0; z < columns; z++) {
var temp_height = 0;
_container.find('.c' + z).each(function () {
temp_height += $(this).outerHeight();
});
column_heights[z] = temp_height;
}
largest = Math.max.apply(Math, column_heights);
_container.css('height', largest + (this.options.padding_y +
this.options.margin_bottom));
};
Plugin.prototype.make_layout_change = function (_self) {
if ($(window).width() < _self.options.single_column_breakpoint) {
_self.calculate(true);
} else {
_self.calculate(false);
}
};
$.fn[pluginName] = function (options) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName,
new Plugin(this, options));
}
});
}
})(jQuery, window, document);
Any tips in getting the Javascript to work would be hugely appreciated!
It is a good practice to have your javascript files right before the closing body tag even though you are using jQuery and other open source libraries. Have you inspected the browser(F12 on windows) to see if the URL that you are pointing to is loading the file on the network? In MVC, you might want to put the JS file inside of bundle.config and referencing them using Bundling and Minification like the following
In Bundle.config
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/scripts").Include(
"~/Scripts/script.js");
In Application_Start Event
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
and
On the UI
#Scripts.Render("~/bundles/scripts")
This way , your JS files are minified and changes are always reflected onto the UI(Solves caching issues)
If you inspect the output html in your browser, you'll see that the url in your script tag probably doesn't resolve correctly:
<script type="text/javascript" src='#Url.Content("~/Scripts/ResponsiveGrid.js")'>
</script>
You can fix this by using a url relative to the root of the domain.
src="/Scripts/ResponsiveGrid.js"
Related
I have a javascript/jquery slideshow but I want to remove the somewhat long blank nothingness in between the fadein and fadeout images. I tried using a small delay because by default it still had a blank pause but that didn't work, any idea?
jsfiddle: https://jsfiddle.net/jzhang172/s624zn7d/1/
var imagesArray = ["http://assets.pokemon.com/assets/cms2/img/pokedex/full//007.png",
"http://assets.pokemon.com/assets/cms2/img/pokedex/full/001.png",
"https://assets.pokemon.com/static2/_ui/img/account/sign-up.png",
"http://static.giantbomb.com/uploads/scale_small/0/6087/2438704-1202149925_t.png",
"http://static.giantbomb.com/uploads/scale_small/0/6087/2438704-1202149925_t.png"];
function preloadImg(pictureUrls, callback) {
var i, j, loaded = 0;
var imagesArray = [];
for (i = 0, j = pictureUrls.length; i < j; i++) {
imagesArray.push(new Image());
}
for (i = 0, j = pictureUrls.length; i < j; i++) {
(function (img, src) {
img.onload = function () {
if (++loaded == pictureUrls.length && callback) {
callback(imagesArray);
}
};
img.src = src;
}(imagesArray[i], pictureUrls[i]));
}
};
function roll(imagesArray, currentPos){
var slide = $('.parallax-mirror').find('img').attr('src', imagesArray[currentPos].src);
slide.fadeIn(2000, function() {
slide.fadeOut(1500, function() {
currentPos++;
if(currentPos >= imagesArray.length){
currentPos = 0;
}
roll(imagesArray, currentPos);
});
});
}
$(function () {
preloadImg(imagesArray, function (imagesArray) {
roll(imagesArray, 0, 3);
});
});
.featured-wrapper {
height: 500px;
width: 100%;
overflow: hidden;
}
.things {
font-size: 50px;
height: 500px;
width: 100%;
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/parallax.js/1.4.2/parallax.min.js"></script>
<div class="featured-wrapper" data-parallax="scroll" data-image-src="http://assets.pokemon.com/assets/cms2/img/pokedex/full//007.png">
</div>
<div class="things">I'm the stuff underneath</div>
You should use an opacity animation with an easing that fits your needs. You can use jquery ui easings
Okay I have the following code:-
[SEE JSFIDDLE]
HTML:
<div id="header">
<span class="mobile-menu"></span>
</div>
CSS:
#header {
width: 100%;
background: #000000;
height: 100px;
}
.mobile-menu {
position: absolute;
right: 25px;
top: 20px;
background: url(http://planetbounce.m360.co.uk/wp-content/themes/planetbounce/assets/img/buttons/menu-01.png);
background-repeat: no-repeat;
background-size: 26px !important;
height: 26px;
width: 26px;
display: inline-block;
margin: 7px 0;
-webkit-transition-duration: 0.8s;
-moz-transition-duration: 0.8s;
-o-transition-duration: 0.8s;
transition-duration: 0.8s;
}
.mobile-menu-hover {
background: url(http://planetbounce.m360.co.uk/wp-content/themes/planetbounce/assets/img/mobile-menu-hover.png);
}
jQuery:
var imagesArray = ["http://planetbounce.m360.co.uk/wp-content/themes/planetbounce/assets/img/buttons/menu-01.png",
"http://planetbounce.m360.co.uk/wp-content/themes/planetbounce/assets/img/buttons/menu-02.png",
"http://planetbounce.m360.co.uk/wp-content/themes/planetbounce/assets/img/buttons/menu-03.png",
"http://planetbounce.m360.co.uk/wp-content/themes/planetbounce/assets/img/buttons/menu-04.png",
"http://planetbounce.m360.co.uk/wp-content/themes/planetbounce/assets/img/buttons/menu-05.png",
"http://planetbounce.m360.co.uk/wp-content/themes/planetbounce/assets/img/buttons/menu-06.png",
"http://planetbounce.m360.co.uk/wp-content/themes/planetbounce/assets/img/buttons/menu-07.png"];
function preloadImg(pictureUrls, callback) {
var i, j, loaded = 0;
var imagesArray = [];
for (i = 0, j = pictureUrls.length; i < j; i++) {
imagesArray.push(new Image());
}
for (i = 0, j = pictureUrls.length; i < j; i++) {
(function (img, src) {
img.onload = function () {
if (++loaded == pictureUrls.length && callback) {
callback(imagesArray);
}
};
img.src = src;
}(imagesArray[i], pictureUrls[i]));
}
};
function changeImage(background, imagesArray, index, reverse) {
background.css("background-image", "url('" + imagesArray[index].src + "')").fadeIn(10, function() {
if (reverse) {
index--;
if (index == -1) {
return; // stop the interval
}
} else {
index++;
if (index == imagesArray.length) {
return; // stop the interval
}
}
//Fade in the top element
background.fadeOut(10, function () {
//Set the background of the top element to the new background
background.css("background-image", "url('" + imagesArray[index] + "')");
changeImage(background, imagesArray, index, reverse);
});
});
}
jQuery(function () {
/* Preload Image */
preloadImg(imagesArray, function (imagesArray) {
jQuery(".mobile-menu").css("background-image", "url('" + imagesArray[0].src + "')")
jQuery('.mobile-menu').on('click', {imgs: imagesArray}, function (event) {
var background = jQuery(".mobile-menu");
var bi = background.css('background-image');
var index = 0;
var reverse = false;
if (imagesArray[0].src != bi.replace('url("', '').replace('")', '')) {
index = imagesArray.length - 1;
reverse = true;
}
changeImage(background, event.data.imgs, index, reverse);
});
});
});
The Issue:
This works fine in Firefox and Chrome, it transitions between the 7 different images on click, then does the reverse on the second click (toggling).
The problem is when I try this in Safari, it basically goes through the image replacement process then reverts back to the first image for some reason and I can't figure out why?
Any ideas?
It seems to be because Safari returns the background-image without double quotes, but your replace function checks for url(", so it doesn't replace and reverse never gets true.
Instead of replacing you can check using either indexOf or matching using a RegExp, it would be safer and more straightforward. Either:
if ( bi.indexOf(imagesArray[0].src) == -1) {
or
if (imagesArray[0].src != bi.match(/http.+png/)[0]) {
With indexOf: http://jsfiddle.net/u9ske14r/
I am trying to create a slot machine using the following jquery plugin: jquery slot machine
I started with the simple Demo und entered my own list. The Problem I am having is that I need more than just that block which shows 1 line of the list. I need to show what is above and beneath the middle line of the lists. So I made the jSlotsWrapper box bigger.
Now I have the problem that when the lists spin, at the end of the list you see empty space. How can I make that the list has no end? So where the last item in the list is, I want to start again with the list.
EDIT
here is my html file
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Datengut Spielautomat</title>
<style type="text/css">
body {
text-align: center;
position: absolute;
height: 600px;
margin: auto;
top: 0; left: 0; bottom: 0; right: 0;
}
ul {
padding: 0;
margin: 0;
list-style: none;
}
li {
height: 62px;
}
.jSlots-wrapper {
overflow: hidden;
text-align: center;
font-family:arial,helvetica,sans-serif;
font-size: 40px;
text-shadow: 2px 2px 2px #888888;
height: 600px;
width: 1242px;
margin: 10px auto;
border: 2px solid;
border-color: #ffa500;
box-shadow: 5px 5px 5px #888888;
box-shadow: inset 0 200px 100px -100px #555555, inset 0 -200px 100px -100px #555555;
}
.jSlots-wrapper::after {
content: "";
background:url("blumen.jpg");
opacity: 0.5;
z-index: -1;
}
.slot {
z-index: -1;
width: 410px;
text-align: center;
margin-left: 5px auto;
margin-right: 5px auto;
float: left;
border-left: 2px solid;
border-right: 2px solid;
border-color: #ffa500;
}
.line {
width: 410px;
height: 2px;
-webkit-transform:
translateY(-20px)
translateX(5px)
}
</style>
</head>
<body>
<ul class="slot">
<li>Bauakte</li>
<li></li>
<li>Bautagebuch</li>
<li></li>
<li>Mängelverwaltung</li>
<li></li>
<li>Störungsverwaltung</li>
<li></li>
<li>Personalakte</li>
<li></li>
<li>Maschinenakte</li>
<li></li>
</ul>
<script src="jquery.1.6.4.min.js" type="text/javascript" charset="utf-8"></script>
<script src="jquery.easing.1.3.js" type="text/javascript" charset="utf-8"></script>
<script src="jquery.jSlots.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
// normal example
$('.slot').jSlots({
number : 3,
spinner : 'body',
spinEvent : 'keypress',
easing: 'easeOutSine',
time : 7000,
loops : 6,
});
</script>
</body>
</html>
and here is my js file:
(function($){
$.jSlots = function(el, options){
var base = this;
base.$el = $(el);
base.el = el;
base.$el.data("jSlots", base);
base.init = function() {
base.options = $.extend({},$.jSlots.defaultOptions, options);
base.setup();
base.bindEvents();
};
// --------------------------------------------------------------------- //
// DEFAULT OPTIONS
// --------------------------------------------------------------------- //
$.jSlots.defaultOptions = {
number : 3, // Number: number of slots
winnerNumber : 1, // Number or Array: list item number(s) upon which to trigger a win, 1-based index, NOT ZERO-BASED
spinner : '', // CSS Selector: element to bind the start event to
spinEvent : 'click', // String: event to start slots on this event
onStart : $.noop, // Function: runs on spin start,
onEnd : $.noop, // Function: run on spin end. It is passed (finalNumbers:Array). finalNumbers gives the index of the li each slot stopped on in order.
onWin : $.noop, // Function: run on winning number. It is passed (winCount:Number, winners:Array)
easing : 'swing', // String: easing type for final spin
time : 7000, // Number: total time of spin animation
loops : 6 // Number: times it will spin during the animation
};
// --------------------------------------------------------------------- //
// HELPERS
// --------------------------------------------------------------------- //
base.randomRange = function(low, high) {
return Math.floor( Math.random() * (1 + high - low) ) + low;
};
// --------------------------------------------------------------------- //
// VARS
// --------------------------------------------------------------------- //
base.isSpinning = false;
base.spinSpeed = 0;
base.winCount = 0;
base.doneCount = 0;
base.$liHeight = 0;
base.$liWidth = 0;
base.winners = [];
base.allSlots = [];
// --------------------------------------------------------------------- //
// FUNCTIONS
// --------------------------------------------------------------------- //
base.setup = function() {
// set sizes
var $list = base.$el;
var $li = $list.find('li').first();
base.$liHeight = $li.outerHeight();
base.$liWidth = $li.outerWidth();
base.liCount = base.$el.children().length;
base.listHeight = base.$liHeight * base.liCount;
base.increment = (base.options.time / base.options.loops) / base.options.loops;
$list.css('position', 'relative');
$li.clone().appendTo($list);
base.$wrapper = $list.wrap('<div class="jSlots-wrapper"></div>').parent();
// remove original, so it can be recreated as a Slot
base.$el.remove();
// clone lists
for (var i = base.options.number - 1; i >= 0; i--){
base.allSlots.push( new base.Slot() );
}
};
base.bindEvents = function() {
$(base.options.spinner).bind(base.options.spinEvent, function(event) {
if (event.which == 32) {
if (!base.isSpinning) {
base.playSlots();
}
}
});
};
// Slot constructor
base.Slot = function() {
this.spinSpeed = 0;
this.el = base.$el.clone().appendTo(base.$wrapper)[0];
this.$el = $(this.el);
this.loopCount = 0;
this.number = 0;
};
base.Slot.prototype = {
// do one rotation
spinEm : function() {
var that = this;
that.$el
.css( 'top', -base.listHeight )
.animate( { 'top' : '0px' }, that.spinSpeed, 'linear', function() {
that.lowerSpeed();
});
},
lowerSpeed : function() {
this.spinSpeed += base.increment;
this.loopCount++;
if ( this.loopCount < base.options.loops ) {
this.spinEm();
} else {
this.finish();
}
},
// final rotation
finish : function() {
var that = this;
var endNum = base.randomRange( 1, base.liCount );
while (endNum % 2 == 0) {
endNum = base.randomRange( 1, base.liCount );
}
var finalPos = - ( (base.$liHeight * endNum) - base.$liHeight );
var finalSpeed = ( (this.spinSpeed * 0.5) * (base.liCount) ) / endNum;
that.$el
.css( 'top', -base.listHeight )
.animate( {'top': finalPos}, finalSpeed, base.options.easing, function() {
base.checkWinner(endNum, that);
});
}
};
base.checkWinner = function(endNum, slot) {
base.doneCount++;
// set the slot number to whatever it ended on
slot.number = endNum;
// if its in the winners array
if (
( $.isArray( base.options.winnerNumber ) && base.options.winnerNumber.indexOf(endNum) > -1 ) ||
endNum === base.options.winnerNumber
) {
// its a winner!
base.winCount++;
base.winners.push(slot.$el);
}
if (base.doneCount === base.options.number) {
var finalNumbers = [];
$.each(base.allSlots, function(index, val) {
finalNumbers[index] = val.number;
});
if ( $.isFunction( base.options.onEnd ) ) {
base.options.onEnd(finalNumbers);
}
if ( base.winCount && $.isFunction(base.options.onWin) ) {
base.options.onWin(base.winCount, base.winners, finalNumbers);
}
base.isSpinning = false;
}
};
base.playSlots = function() {
base.isSpinning = true;
base.winCount = 0;
base.doneCount = 0;
base.winners = [];
if ( $.isFunction(base.options.onStart) ) {
base.options.onStart();
}
$.each(base.allSlots, function(index, val) {
this.spinSpeed = 250*index;
this.loopCount = 0;
this.spinEm();
});
};
base.onWin = function() {
if ( $.isFunction(base.options.onWin) ) {
base.options.onWin();
}
};
// Run initializer
base.init();
};
// --------------------------------------------------------------------- //
// JQUERY FN
// --------------------------------------------------------------------- //
$.fn.jSlots = function(options){
if (this.length) {
return this.each(function(){
(new $.jSlots(this, options));
});
}
};
})(jQuery);
The core functionality is the same as in the github repository.
The important part, I think, is the function spinEm:
spinEm : function() {
var that = this;
that.$el
.css( 'top', -base.listHeight )
.animate( { 'top' : '0px' }, that.spinSpeed, 'linear', function() {
that.lowerSpeed();
});
}
here the list is placed above the jSlotsWrapper and with the animate function it moves down. Now what I need is for the animation to continue, and not to place the list at the top again. How can I achieve that.
EDIT
Ok, i tried the following to avoid the empty space, everytime the animation has finished:
spinEm : function() {
var that = this;
that.$el
.css( 'bottom', $("body").height() )
.animate( { 'top' : '0px' }, that.spinSpeed, 'linear', function() {
that.lowerSpeed();
});
}
I try to place the list at the bottom of the box and move it down until the top appears. But somehow the list doesn't really move. It just moves for 1 word and then stops comletely. What is wrong in the animation code?
EDIT
Ok I found the solution to my problem. Apparently, I can't use bottom in the css function. Instead, I used top and calculated the position of the top border of the list. That way I have an animation without all the empty space at the beginning. To avoid the jumping from the bottom to the top of the list I modified the height of the jSlots-Wrapper and the order of the list items, so that the items that are displayed before and after the jump are the same. That way, the user doesn't see the list jumping.
here is my new animate function.
spinEm : function() {
var that = this;
that.$el
.css( 'top', -(base.listHeight - $("body").height()) )
.animate( { 'top' : '0px'}, that.spinSpeed, 'linear', function() {
that.lowerSpeed();
});
}
I found a way to make the animation so that the user doesn't see the jumping. What I did, is, I configured the list in a way so that the beginning and the end are the same. So that when the end of the list is reached and it jumps to the beginning again, there is no difference. The jump is still there, but not visible for the user.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I wrote this Javascript application for a 15-puzzle. The entire application is contained in the file below. Whenever I render a new board, I'm trying to store the initial configuration in the initialBoard variable so I can replay the same game later. However, initialBoard variable always seems to equal the currentBoard variable. I'm new to Javascript and any help will be greatly appreciated.
<html>
<head>
<title>15 Puzzle</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<style type="text/css">
#puzzle-board {
border: 5px solid;
}
.puzzle-tile {
background:#fff;
background: -moz-linear-gradient(top, #fff, #eee);
background: -webkit-gradient(linear,0 0, 0 100%, from(#fff), to(#eee));
box-shadow: inset 0 0 0 1px #fff;
-moz-box-shadow: inset 0 0 0 1px #fff;
-webkit-box-shadow: inset 0 0 0 1px #fff;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size:60px;
height: 100px;
text-align: center;
text-decoration: none;
text-shadow:0 1px #fff;
user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
vertical-align:middle;
width: 100px;
}
#start-stop {
float: left;
}
#timer {
float: left;
margin-left: 10px;
}
#counter {
float: left;
margin-left: 10px;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row">
<br />
</div>
<div class="row">
<div class="col-md-5 col-md-offset-1">
<table id="puzzle"></table>
</div>
<div class="col-md-6">
<div class="row">
<br />
<button type="button" class="btn btn-lg btn-success" id="start-stop">START</button>
<button type="button" class="btn btn-lg btn-default" id="timer"></button>
<button type="button" class="btn btn-lg btn-default" id="counter"></button>
</div>
</div>
</div>
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<!--<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>-->
<script>
/**
* Puzzle Object
*/
puzzle = function(targetId) {
/************************************************************
* Private members
************************************************************/
var
currentBoard,
initialBoard,
orderedBoard = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,'']];
function canSwapTiles(source, target) {
var sourceTileRow = source.attr("data-row");
var sourceTileCol = source.attr("data-col");
var sourceTileValue = source.text();
var targetTileRow = target.attr("data-row");
var targetTileCol = target.attr("data-col");
var targetTileValue = target.text();
if (sourceTileValue != '' && targetTileValue != '') {
return false;
} else if (Math.abs(targetTileRow - sourceTileRow) > 1) {
return false;
} else if (Math.abs(targetTileCol - sourceTileCol) > 1) {
return false;
} else {
return true;
}
}
function swapTiles(source, target) {
var sourceTileRow = source.attr("data-row");
var sourceTileCol = source.attr("data-col");
var sourceTileValue = source.text();
var targetTileRow = target.attr("data-row");
var targetTileCol = target.attr("data-col");
var targetTileValue = target.text();
source.text(targetTileValue);
currentBoard[sourceTileRow][sourceTileCol] = parseInt(targetTileValue);
target.text(sourceTileValue);
currentBoard[targetTileRow][targetTileCol] = parseInt(sourceTileValue);
$(targetId).trigger('moved');
console.log("swapped tiles");
console.log(initialBoard);
if (isSolved())
{
console.log('solved puzzle');
console.log(initialBoard);
$(targetId).trigger('solved', {
board: initialBoard
});
}
}
function renderBoard(board) {
$("#puzzle-board").empty();
currentBoard = board;
//initialBoard = board;
console.log('rendering board');
console.log(initialBoard);
for (i = 0; i < 4; i++) {
$("#puzzle-board").append('<tr class="puzzle-row" id="puzzle-row-' + i + '"></tr><br />');
for (j = 0; j < 4; j++) {
var tile = '<td class="puzzle-tile" data-row="' + i + '" data-col="' + j + '">' +
board[i][j] +
'</td>';
$("#puzzle-row-" + i).append(tile);
}
}
$(".puzzle-tile").draggable(
{
revert: true,
snap: true,
snapMode: "inner",
zIndex: 100
}
).droppable(
{
drop: function (event, ui) {
var sourceTile = ui.draggable;
var targetTile = $(this);
if (canSwapTiles(sourceTile, targetTile)) {
swapTiles(sourceTile, targetTile);
}
}
}
);
}
function randomBoard() {
var tileValues = [];
for (i = 0; i < 15; i++) {
tileValues[i] = i + 1;
}
var randomlyOrderedTileValues = [''];
do {
randomlyOrderedTileValues[(16 - tileValues.length)] = tileValues.splice(Math.floor(Math.random() * tileValues.length), 1).pop();
} while (tileValues.length > 0);
var board = [];
for (i = 0; i < 4; i++) {
board[i] = [];
for (j = 0; j < 4; j++) {
board[i][j] = randomlyOrderedTileValues.pop();
}
}
return board;
}
function isSolved() {
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
if (isNaN(currentBoard[i][j]))
{
continue;
}
if (parseInt(currentBoard[i][j]) != parseInt(orderedBoard[i][j]))
{
return false;
}
}
}
return true;
}
/************************************************************
* Constructor
************************************************************/
/*
* Initialize board
*/
$(targetId).append('<tbody id="puzzle-board"></tbody>');
renderBoard(orderedBoard);
/************************************************************
* Public data and methods
************************************************************/
return {
reset: function() {
renderBoard(orderedBoard);
},
shuffle: function() {
//initialBoard = randomBoard();
initialBoard = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,'',15]];
renderBoard(initialBoard);
}
}
};
/**
* Timer Object
*/
timer = function(targetId) {
/************************************************************
* Private members
************************************************************/
var
intervalId,
totalSeconds = 0;
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
function setTime()
{
++totalSeconds;
$("#seconds").html(pad(totalSeconds % 60));
$("#minutes").html(pad(parseInt(totalSeconds / 60)));
}
/************************************************************
* Constructor
************************************************************/
/*
* Initialize timer
*/
$(targetId).append('<i>Time: </i><i id="minutes">00</i>:<i id="seconds">00</i>');
/************************************************************
* Public data and methods
************************************************************/
return {
reset: function() {
window.clearInterval(intervalId);
totalSeconds = 0;
$("#minutes").text('00');
$("#seconds").text('00');
},
start: function () {
intervalId = window.setInterval(setTime, 1000);
},
getTime: function () {
return pad(parseInt(totalSeconds / 60)) + ':' + pad(totalSeconds % 60);
}
}
};
/**
* Counter Object
*/
counter = function(targetId) {
/************************************************************
* Private members
************************************************************/
var
steps = 0;
/************************************************************
* Constructor
************************************************************/
/*
* Initialize timer
*/
$(targetId).append('<i id="steps-title">Steps: </i><i id="steps-count">0</i>');
/************************************************************
* Public data and methods
************************************************************/
return {
reset: function() {
steps = 0;
$("#steps-count").text(steps);
},
incr: function () {
steps++;
$("#steps-count").text(steps);
},
getSteps: function () {
return steps;
}
}
};
$(document).ready(function() {
var Puzzle = puzzle("#puzzle");
var Timer = timer("#timer");
var Counter = counter("#counter");
localStorage["games"] = '[]';
$("#start-stop").click(function() {
switch ($(this).text()) {
case 'START':
$(this).removeClass("btn-success").addClass("btn-danger").text("STOP");
Puzzle.shuffle();
Timer.start();
Counter.reset();
break;
case 'STOP':
$(this).removeClass("btn-danger").addClass("btn-success").text("START");
Puzzle.reset();
Timer.reset();
Counter.reset();
break;
}
});
$("#puzzle").bind('moved',
function(e, data) {
Counter.incr();
}
).bind('solved',
function(e, data) {
console.log(data);
$("#start-stop").removeClass("btn-danger").addClass("btn-success").text("START");
Puzzle.reset();
Timer.reset();
Counter.reset();
}
);
});
</script>
</body>
When you invoke the Puzzle.shuffle() here:
$("#start-stop").click(function() {
switch ($(this).text()) {
case 'START':
$(this).removeClass("btn-success").addClass("btn-danger").text("STOP");
Puzzle.shuffle();
Timer.start();
Counter.reset();
break;
case 'STOP':
$(this).removeClass("btn-danger").addClass("btn-success").text("START");
Puzzle.reset();
Timer.reset();
Counter.reset();
break;
}
});
It initializes the board and passes it to renderBoard here
shuffle: function() {
//initialBoard = randomBoard();
initialBoard = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,'',15]];
renderBoard(initialBoard);
}
Then renderBoard does this:
currentBoard = board;
Which causes both variables point to the same object. If you want them to be separated, then in renderBoard you should clone the object, instead of assigning it. Something along the lines of this if you use jQuery:
currentBoard = [];
$.extend(currentBoard, board);
I created a plug-in to display a Metro MessageBar and it works great. I was asked to support callbacks and added some code to the fadeIn functionality for this purpose.
For some reason, the callback shows as a valid function, but doesn't call?
HERE IS THE CONSOLE MESSAGE I AM GETTING:
this.trigger is not a function
...any help is appreciated.
THIS IS HOW TO USE THE PLUG-IN:
this.showSubmitMessage = function () {
var options = {
message: "This is a test.",
messageType: "information"
};
// self.btnSubmit.click IS a valid function!!! Use your own if you want.
nalco.es.rk.globals.messageBarManager.display(options, self.btnSubmit.click);
};
THIS IS THE OFFENDING AREA-OF-CODE IN THE PLUG-IN:
this.fadeIn = function (element, callback) {
element.prependTo(self.container).centerToScrollTop().fadeIn(self.globals.fadeDuration, function() {
if (callback != null)
if ($.isFunction(callback))
setTimeout(function () {
callback();
}, self.globals.callbackDuration);
});
};
THIS IS THE ENTIRE USER-CONTROL PLUG-IN:
Please notice the code for the file-dependency "jquery.Extensions.js" is at the bottom of this posting.
<script src="Scripts/jQuery/Core/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="Scripts/jQuery/Core/jquery.tmpl.js" type="text/javascript"></script>
<script src="Scripts/jQuery/jquery.Extensions.js" type="text/javascript"></script>
<style type="text/css">
.messageBar { background-color: #DDDDDD; color: #666666; display: none; left: 0; padding: 15px; position: absolute; top: 0; width: 932px; z-index: 1000; }
.messageBar .content { width: 100%; }
.messageBar .content td.image { width: 70px; }
.messageBar .content td.button { width: 60px; }
.messageBar .button { margin-top: 0px; }
.messageBar .content .icon { background-repeat: no-repeat; height: 31px; overflow: hidden; width: 31px; }
.messageBar .content .message { }
.messageBar .content .image { background-repeat: no-repeat; height: 10px; overflow: hidden; width: 70px; }
.messageBar.error { background-color: #FFBABA; color: #D8000C; }
.messageBar.information { background-color: #99CCFF; color: #00529B; }
.messageBar.success { background-color: #DFF2BF; color: #4F8A10; }
.messageBar.warning { background-color: #FEEFB3; color: #9F6000; }
.messageBar.error .content .icon { background-image: url('/_layouts/images/error.png'); }
.messageBar.information .content .icon { background-image: url('/_layouts/images/info.png'); }
.messageBar.success .content .icon { background-image: url('/_layouts/images/success.png'); }
.messageBar.warning .content .icon { background-image: url('/_layouts/images/warning.png'); }
</style>
<script id="template-messageBar" type="text/html">
<div class="messageBar">
<table class="content">
<tbody>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td class="button">
<input type="button" value="Close" class="button metroButton" />
</td>
</tr>
</tbody>
</table>
</div>
</script>
<script id="template-messageBar-icon" type="text/html">
<div class="icon">
</div>
</script>
<script id="template-messageBar-message" type="text/html">
<div class="message">
${Message}
</div>
</script>
<script id="template-messageBar-image" type="text/html">
<div class="image">
</div>
</script>
<script type="text/javascript">
;nalco.es.rk.source.MessageBarManager = (function ($) {
var publicInstances = {};
publicInstances.Controller = Controller;
function Controller(options) {
var self = this;
this.messageTypes = { error: "error", information: "information", normal: null, success: "success", warning: "warning" };
this.globals = {
callbackDuration: 2000,
fadeDuration: 700,
workingImageUrl: "url('/_layouts/images/Nalco.ES.SharePoint.UI/metro-ajax-loader-blue.gif')"
};
this.defaults = {
message: "",
messageType: self.messageTypes.normal,
showIcon: false,
showWorkingImage: false
};
this.container = $('body');
this.templateMessageBarId = '#template-messageBar';
this.templateMessageBarIconId = '#template-messageBar-icon';
this.templateMessageBarMessageId = '#template-messageBar-message';
this.templateMessageBarImageId = '#template-messageBar-image';
this.selectors = { content: '.content', closeButton: '.button', root: '.messageBar' };
this.initialize = function () {
self.display(options);
};
this.display = function (options, callback) {
var empty = {};
var settings = $.extend(empty, self.defaults, $.isPlainObject(options) ? options : empty);
if (settings.messageType != null)
if (settings.messageType.length == 0)
settings.messageType = self.messageTypes.normal;
if (settings.message.length == 0)
return;
var eleMessageBar = $(self.templateMessageBarId).tmpl(empty);
var eleContent = $(self.selectors.content, eleMessageBar);
var eleCellOne = $('td:eq(0)', eleContent);
var eleCellTwo = $('td:eq(1)', eleContent);
var eleCellThree = $('td:eq(2)', eleContent);
var eleMessage = $(self.templateMessageBarMessageId).tmpl({ Message: settings.message });
var btnClose = $(self.selectors.closeButton, eleMessageBar);
if (settings.messageType != self.messageTypes.normal) {
eleMessageBar.addClass(settings.messageType);
if (settings.showIcon) {
var eleIcon = $(self.templateMessageBarIconId).tmpl(empty);
eleCellOne.css('width', '31px');
eleIcon.appendTo(eleCellOne);
}
}
eleMessage.appendTo(eleCellTwo);
btnClose.click(function () {
eleMessageBar.fadeOut(self.globals.fadeDuration, function () {
eleMessageBar.remove();
});
});
if (settings.showWorkingImage) {
var eleImage = $(self.templateMessageBarImageId).tmpl(empty);
eleCellThree.addClass('image');
eleImage.css('background-image', self.globals.workingImageUrl);
eleImage.appendTo(eleCellThree);
}
var elePreviousMessage = $(self.selectors.root, self.container);
if (elePreviousMessage.length > 0) {
btnClose = $(self.selectors.closeButton, elePreviousMessage);
btnClose.click();
setTimeout(function () { self.fadeIn(eleMessageBar, callback); }, self.globals.fadeDuration);
}
else
self.fadeIn(eleMessageBar, callback);
};
this.fadeIn = function (element, callback) {
element.prependTo(self.container).centerToScrollTop().fadeIn(self.globals.fadeDuration, function() {
if (callback != null)
if ($.isFunction(callback))
setTimeout(function () {
callback();
}, self.globals.callbackDuration);
});
};
self.initialize();
};
return publicInstances;
})(jQuery);
function initializeMessageBarManager() {
nalco.es.rk.globals.messageBarManager = new nalco.es.rk.source.MessageBarManager.Controller();
}
$(document).ready(function () {
initializeMessageBarManager();
if (typeof (Sys) != "undefined")
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(initializeMessageBarManager);
});
</script>
THIS IS THE EXTENSIONS DEPENDENCY LISTED IN THE FILES ABOVE:
// **********************
// .centerToScrollTop
// Use -
// Centers an ELEMENT to the window's scrollTop.
//
// Example -
// $('.myElement').centerToScrollTop();
// **********************
(function ($) {
$.fn.extend({
centerToScrollTop: function (options) {
return this.each(function () {
var element = $(this);
var container = $(window);
var scrollTop = container.scrollTop();
var buffer = 30;
var top = scrollTop + buffer;
var left = (container.width() - element.outerWidth()) / 2 + container.scrollLeft();
element.css({ 'position': 'absolute', 'top': top, 'left': left });
return element;
});
}
});
})(jQuery);
This type of error occurs usually if you forgot to include some files like jquery-ui.min.js etc. Check carefully if you add all the necessary references.