I am creating a checker variation game.
I am new to jquery but through some help the pieces can now move around the board.
Is there a way to indicate the start location and end location of a move?
I would also like to disable all piece movement once a move has been made.
current code:
$('img').draggable();
$('#tbl td').droppable({
hoverClass: 'over',
drop: function(event, ui) {
var cell = ui.draggable.appendTo($(this)).css({
'left': '0',
'top': '0'
});
var row = cell.closest('tr').prevAll().length + 1;
var col = cell.closest('td').prevAll().length + 1;
$('#coords').html('Row ' + row + ', Col ' + col);
}
});
jsfiddle http://jsfiddle.net/blueberrymuffin/bLb3H/
thanks.
$('img').draggable({
start: function(e, ui) {
alert('Starting move from position (' + ui.position.top + ', ' + ui.position.left + ')');
},
stop: function(e, ui) {
alert('Ending move at position (' + ui.position.top + ', ' + ui.position.left + ')');
}
});
$('#tbl td').droppable({
hoverClass: 'over',
drop: function(event, ui) {
var cell = ui.draggable.appendTo($(this)).css({
'left': '0',
'top': '0'
});
var row = cell.closest('tr').prevAll().length + 1;
var col = cell.closest('td').prevAll().length + 1;
$('#coords').html('Row ' + row + ', Col ' + col);
$('img').draggable('disable');
}
});
I think I figured it out.
Here is the code:
$('img').draggable({
start: function(e, ui) {
var myCol = $(this).closest("td").index() + 1;
var myRow = $(this).closest("tr").index() + 1;
$('#coords').html('Row ' + myRow + ', Col ' + myCol);
},
});
$('#tbl td').droppable({
hoverClass: 'over',
drop: function(event, ui) {
var cell = ui.draggable.appendTo($(this)).css({
'left': '0',
'top': '0'
});
var row = cell.closest('tr').prevAll().length + 1;
var col = cell.closest('td').prevAll().length + 1;
$('#coords').html('Row ' + row + ', Col ' + col);
$('img').draggable('disable');
}
});
and the jsfiddle: http://jsfiddle.net/bLb3H/5/
I am not sure though how to replace the current image with the new one that was dragged onto it (currently both images occupy the same cell). Any ideas?
Thanks.
Related
My div contains records which are added dynamically. When I click on the 'Remove' link it generates a confirm box 3 times if I have 3 record, 5 times if I have 5 records and so on.
I want to display the confirm box for that particular row only. How can I do that?
```
<script type="text/javascript">
$(document).ready(function () {
$("#<%= imagehs.ClientID %>").on("click", function (event) {
$("#textboxX").html("");
$("#textboxY").html("");
$("#textboxBPart").html("");
$("#divSaveDynamicDis").html("");
var values = new Array();
var x = event.pageX;
var y = event.pageY;
//$(".marker").remove();
$("body").append(
// $('<div class="marker"></div>').css({
//$('<div class="marker m_' + x + '_' + y + '" divdata-marker="m_' + x + '_' + y + '"></div>').css({
$('<div class="marker m_' + x + '_' + y + '"></div>').css({
position: 'absolute',
top: y + 'px',
left: x + 'px',
//top: event.pageY + 'px',
//left: event.pageX + 'px',
width: '10px',
height: '10px',
background: '#dd4b39',
'border-radius': '10px'
})
);
$("#textboxX").append('<div><input type="text" value="' + x + '" id="txtX" name="txtX"/></div>');
$("#textboxY").append('<div><input type="text" value="' + y + '" id="txtY" name="txtY"/></div>');
$("#textboxBPart").append("<div><input type='text' id='txtName' name='txtName'/></div>");
var $r = $('<button />', { type: 'button', text: 'Refresh Data', id: 'btn_refresh' });
var $cancle = $('<button />', { type: 'button', text: 'Cancle', id: 'btn_cancle' });
$("#divSaveDynamicDis").append($r);
$("#divSaveDynamicDis").append($cancle);
$r.on('click', function () {
if ($('input#txtName').val() == "") {
alert('Please complete the field');
$('input#txtName').focus();
return false;
}
//var NewData = '<div cla-ss="col-sm-12">' + x + ' ' + y + ' ' + txtName.value + ' <a href="javascript:void(0);" class="remCF" data-atrib=' + x +'>Remove</a> </div>';
//var NewData = '<div class="col-sm-12">' + x + ' ' + y + ' ' + txtName.value + ' Remove </div>';
var NewData = '<div class="col-sm-12">' + x + ' ' + y + ' ' + txtName.value + ' Remove </div>';
$("#divdynamicData").append(NewData);
$("#textboxX").html("");
$("#textboxY").html("");
$("#textboxBPart").html("");
$("#divSaveDynamicDis").html("");
});
$('.marker').on('click', function () {
$(this).remove();
// div_ref = $(this).attr('divdata-marker')
// $('#divdynamicData.' + div_ref).remove()
});
//$("#divdynamicData").live('click', '.remCF', function () {
//$("#divdynamicData").on('click', '.remCF', function () {
// //if (confirm("Are you sure?")) {
// marker_ref = $(this).attr('data-marker')
// $('.marker.' + marker_ref).remove()
// $(this).parent().remove();
// //}
// //return false;
//});
$("#divdynamicData").on('click', '.remCF', function () {
// if (confirm("Are you sure you want to delete?")) {
marker_ref = $(this).attr('data-marker')
$('.marker.' + marker_ref).remove()
$(this).parent().remove();
// }
});
$cancle.on('click', function () {
$("#textboxX").html("");
$("#textboxY").html("");
$("#textboxBPart").html("");
$("#divSaveDynamicDis").html("");
});
});
});
```
$("#textboxX").append('<div><input type="text" value="' + x + '" id="txtX" name="txtX"/></div>');
$("#textboxY").append('<div><input type="text" value="' + y + '" id="txtY" name="txtY"/></div>');
$("#textboxBPart").append("<div><input type='text' id='txtName' name='txtName'/></div>");
var NewData = '<div class="col-sm-12">' + x + ' ' + y + ' ' + txtName.value + ' Remove </div>';
$("#divdynamicData").append(NewData);
$("#divdynamicData").on('click', '.remCF', function() {
// if (confirm("Are you sure you want to delete?")) {
marker_ref = $(this).attr('data-marker')
$('.marker.' + marker_ref).remove()
$(this).parent().remove();
// }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-6">
<asp:Image id="imagehs" name="imagehs" runat="server" Height="500" Width="500" />
<div id="textboxX"></div>
<div id="textboxY"></div>
<div id="textboxBPart"></div>
<div id="divSaveDynamicDis"></div>
<div id="divdynamicData"></div>
</div>
You're short circuting your code by returning the value of the confirm. In other words, once you return the value of confirm, none of the code below it will fire. Instead, you want to check what the user has chosen from the confirm via a conditional and place your removal code in the proceeding block:
$("#divdynamicData").on('click', '.remCF', function() {
if (confirm("Are you sure you want to delete?")) {
var marker_ref = $(this).attr('data-marker');
$('.marker.' + marker_ref).remove();
$(this).parent().remove();
}
});
I assume you are using this code inside a loop or inside another event. The code below should be removed from this loop/event and only be used one time in your page:
$("#divdynamicData").on('click', '.remCF', function () {
// if (confirm("Are you sure you want to delete?")) {
marker_ref = $(this).attr('data-marker')
$('.marker.' + marker_ref).remove()
$(this).parent().remove();
// }
});
Because it is a delegate click, each time you declare this code, a new event listener will be attatched to your div listening to clicks on .remCF so multiple events will be fired on your click.
See more: JQuery API .on()
I am trying to dynamically change my page content when the slider values are changed. At the moment the user sets the slider, clicks a button below and content is displayed. When the sliders are changed again, the user has to click the button again to reload the content (because each button is assigned to the goalkeeperstat function.
<a class="chosenstat" title="Saves" value="saves" name="save" onclick="goalkeeperstat(this);">Saves</a>
Rather than having to press the button again I would like the content to change as soon as the user drags the slider handles to their chosen values.
Below is a screenshot of my page.
http://i.imgur.com/eZq08sI.jpg
$(function initSlider() {
$("#slider1").slider({
range: true,
min: 0,
max: 100,
values: [0, 100],
slide: function update1 (event, ui) {
$(".amount").val(ui.values[0] + " - " + ui.values[1]);
slidervalueg1 = $('#g1').val(ui.values[0]);
slidervalueg2 = $('#g2').val(ui.values[1]);
}
});
$(".amount").val($("#slider1").slider("values", 0) +
" - " + $("#slider1").slider("values", 1));
});
function goalkeeperstat(element){
$('#result1').empty();
$('.amount').empty();
var category = element.getAttribute("value");
var categoryprompt = element.getAttribute("title");
var infocategory = element.getAttribute("name");
var position = 1;
var fr = $(myjson).filter(function (i,n){return n.element_type===position & n[category] >= slidervalueg1.val() && n[category] <= slidervalueg2.val() });
for (var i=0;i<fr.length;i++)
{
document.getElementById('result1').innerHTML += ("<div class='profile'><img src='https://platform-static-files.s3.amazonaws.com/premierleague/photos/players/110x140/p" + fr[i].code + ".png'/><div class='playerinfo'><p>Name: " + fr[i].first_name + " " + fr[i].second_name + "</p><p>Position: " + posdictionary[fr[i].element_type.toString()] + "</p><p class='teamname'>Team: " + dictionary[fr[i].team.toString()] + "</p><p>" + categoryprompt + ": <span class='categoryprompt'>" + fr[i][category] + "</span></p></div><div class='infobg'><p>Minutes: " + fr[i].minutes + "</p><p>Minutes per " + infocategory + ": " + parseFloat(Math.round((fr[i].minutes / fr[i][category]) * 100) / 100).toFixed(2) + "</p></div></div>");
}
}
EDIT: Tried using "stop" but it wouldn't work. Any other tips?
you can use event or method explicit :
$("#slider1").slider({
range: true,
min: 0,
max: 100,
values: [0, 100],
slide: function update1 (event, ui) {
$(".amount").val(ui.values[0] + " - " + ui.values[1]);
slidervalueg1 = $('#g1').val(ui.values[0]);
slidervalueg2 = $('#g2').val(ui.values[1]);
},
stop : function(event, ui){
console.log("slider changed");
// call your fucntion here
}
});
I'm using the .each function to hide/show columns of a table. But the problem is that the code is very slow in IE. After searching on internet I saw that could be because of my .each() function and $(this).
For more information why I'm using this code, you can look at this post: Hide/show column
This is my old code:
include JQuery.min.js on page
javascript:
$(function () {
$('table th').each(function (_id, _value) {
if(_id > 2){
if($(this).find("a").text()){
$('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$(this).find("a").text()+'</div></span>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(_id + 1) + '),table th:nth-of-type(' + parseInt(_id + 1) + ')').toggle();
e.preventDefault();
});
}
else{
if($(this).find("div").text()){
$('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$(this).find("div").text()+'</div></span>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(_id + 1) + '),table th:nth-of-type(' + parseInt(_id + 1) + ')').toggle();
e.preventDefault();
});
}
}
}
});
});
HTML:
<div id="togglers">Show/Hide columns<br/></div>
I tried to convert my javascript with this code (Source: jQuery very slow in IE), but I think there is still a problem with my i(or _id) and _value...
$(function () {
var items = $('table th');
var $currentItem;
for (var i = 0, j = items.length; i < j; i++) {
$currentItem = $(items[i]); // in place of $(this)
function (i, _value) {
if(i > 2){
if($currentItem.find("a").text()){
$('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$currentItem.find("a").text()+'</div></span>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(i + 1) + '),table th:nth-of-type(' + parseInt(i + 1) + ')').toggle();
e.preventDefault();
});
}
else{
if($currentItem.find("div").text()){
$('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$currentItem.find("div").text()+'</div></span>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(i + 1) + '),table th:nth-of-type(' + parseInt(i + 1) + ')').toggle();
e.preventDefault();
});
}
}
}
}
}
});
It's possible that I need to use other code. Any suggestion is welcome! Tnx.
Performance issue has nothing to do with .each. DOM is tens of times slower than any way to iterate collection you choose.
Instead of iterating table on every toggle you can make CSS do it for you. Demo.
$(function() {
var togglers = $('#togglers'), //cache toggler ref
addToggler = function(idx, text) {
togglers.append('<span class="toggler" data-id="'
+ idx + '">' + text + '</span>');
},
table = $('#table'), //cache table ref
columns = 0;
//generate styles for 100 columns table :)
(function generateStyleSheet(len){
var styles = [], i = 0;
for(; i < len; i++) {
styles.push('.hide-' + i + ' .column-' + i + ' {display: none;}') ;
}
$('<style>' + styles.join('\n') + '</style>').appendTo(document.body);
}(100))
//bind on click once using event delegation
togglers.on('click', '.toggler', function(e){
var id = $(e.target).toggleClass('pressed').data('id');
table.toggleClass('hide-' + id);
});
//generate all togglers and count em
table.find('th').each(function(idx, header){
header = $(header);
addToggler(idx, header.text()); //make toggler
header.addClass('column-' + idx); //add class column-i
columns++;
});
//add column-i class to tds
table.find('td').each(function(idx, td) {
$(td).addClass('column-' + (idx%columns));
});
});
I'm having issues increasing a variable by 1 every time I scroll. I successfully increase the variable by 1, but only once. This is the code I got. I need to increase the variable page.
$(document).ready(function () {
$(document).scroll(function (e) {
currentPage = 0;
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
++currentPage;
$.getJSON("../campus/Settings/TranslationSettings.ashx?command=show&page=" + currentPage + "&Lang=en", function (data) {
var items = [];
$.each(data.Keys, function (key, val) {
$("<ul/>", {
"class": "translateinfo",
html: "<li class='keystring'><span class='label'>text string:</span>" + val["text string"] + "</li>" + "<li class='autotranslate'><span class='label'>Automated translation:</span>" + val["automated translation"] + "</li>" + "<li class='functionnumber'><span class='label'>Function Number:</span>" + val["function number"] + "</li>" + "<li class='translateurl'><span class='label'>URL:</span>" + val["url"] + "</li>"
}).appendTo("#updatepanel");
});
});
}
});
});
Not sure if you copy/paste your entire code. But you're recreating currentPage everytime the user scroll
Working fiddle, I create the variable before the scroll loop.
var currentPage = 0;
$(document).scroll(function (e) {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
++currentPage;
console.log(currentPage);
}
})
http://jsfiddle.net/dCr3Z/
Hi all i am having some which i am appending to a div dynamically in my view....i have three ajax calls for different methods....firstly i show all the images of product in a div ....and if a user selects the price range the proucts will be displayed of that price range only and same for colours..what i want is i want this when user selects price range or color the div with all images should be replaced with the new images how can i do this can any one help me here
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/api/ProductLayout", function (data) {
$.each(data, function (idx, ele) {
$("#makeMeScrollable").append('ProdcutID'+'<span>' + ele.ProductID +
'</span>ProductName<span>' + ele.ProductName + '</span>Price<span>' + ele.Price + '</span>');
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#makeMeScrollable");
});
scrollablediv();
});
});
function scrollablediv() {
$("div#makeMeScrollable").smoothDivScroll({
mousewheelScrolling: true,
manualContinuousScrolling: true,
visibleHotSpotBackgrounds: "always",
autoScrollingMode: "onstart"
});
}
</script>
<script type="text/javascript">
$(function () {
$("#slider-range").slider({
range: true,
min: 0,
max: 500,
values: [0,0],
slide: function (event, ui) {
$("#amount").val("$" + ui.values[0] + " - $" + ui.values[1]);
},
change: function (event, ui) {
// when the user change the slider
},
stop: function (event, ui) {
// when the user stopped changing the slider
$.get("/api/ProductLayout", { firstPrice: ui.values[0], secondPrice: ui.values[1] }, function (data) {
$.each(data, function (idx, ele) {
$("#makeMeScrollable").append('<lable>ProdcutID:</label>' + '<span>' + ele.ProductID +
'</span><br/><lable>ProductName:</label><span>' + ele.ProductName + '</span><br/><label>Price:</label><span>' + ele.Price + '</span>');
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#makeMeScrollable");
});
});
}
});
$("#amount").val("$" + $("#slider-range").slider("values", 0) +
" - $" + $("#slider-range").slider("values", 1));
});
</script>
<script type="text/javascript">
function getproductbycolor(colours) {
alert(1);
$.get("/api/ProductLayout", { color: colours }, function (data) {
alert(data.toString());
$.each(data, function (idx, ele) {
$("#makeMeScrollable").append('<lable>ProdcutID:</label>' + '<span>' + ele.ProductID +
'</span><br/><lable>ProductName:</label><span>' + ele.ProductName + '</span><br/><label>Price:</label><span>' + ele.Price + '</span><br/><label>Product Color:</label><span>'+ele.ProductColor+'</span>');
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#makeMeScrollable");
});
});
}
</script>
and this is my html
<div id="makeMeScrollable" style="height: 400px; width: 400px;">
</div>
i should append all the images only to the above div replacing the previous images
As said by jaswant you can use .empty() method but not .empty().append() what this does is it will empty the data when ever an new record is binded so use .empty() method before your ajax call or json call
$("#makeMeScrollable").empty();
add the above line before your ajax call
<script type="text/javascript">
function getproductbycolor(colours) {
alert(1);
$("#makeMeScrollable").empty();
$.get("/api/ProductLayout", { color: colours }, function (data) {
alert(data.toString());
$.each(data, function (idx, ele) {
$("#makeMeScrollable").append('<lable>ProdcutID:</label>' + '<span>' + ele.ProductID +
'</span><br/><lable>ProductName:</label><span>' + ele.ProductName + '</span><br/><label>Price:</label><span>' + ele.Price + '</span><br/><label>Product Color:</label><span>'+ele.ProductColor+'</span>');
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#makeMeScrollable");
});
});
}
Try this,
$("#makeMeScrollable").html('ProdcutID<span>' + ele.ProductID +
'</span>ProductName<span>' + ele.ProductName + '</span>Price<span>' +
ele.Price + '</span><img src="' + ele.ImageURL + '" />');
You can always use html() in place of append() to remove the existing content.
or you can do empty the element before append with .empty().append()
EDIT (after comments)
var $div = $("#makeMeScrollable");
$div.empty();
$.each(data, function (idx, ele) {.append('ProdcutID' + '<span>' + ele.ProductID + '</span>ProductName<span>' + ele.ProductName + '</span>Price<span>' + ele.Price + '</span>');
$("<img/>").attr({
src: ele.ImageURL
}).appendTo("#makeMeScrollable");
});
You should do the empty as the first action in your success handler. Because the calls are asynchroneous, you will have the risk of products interfering with each other if you clear the area before you do the ajax call.
$(document).ready(function () {
$.getJSON("/api/ProductLayout").success(function (data) {
clearProductDisplayArea();
displayProductInfo(data);
scrollablediv();
});
});
function clearProductDisplayArea(){
$("#makeMeScrollable").empty();
}
function displayProductInfo(data){
$.each(data, function (idx, ele) {
$("#makeMeScrollable").append('ProdcutID'+'<span>' + ele.ProductID +
'</span>ProductName<span>' + ele.ProductName + '</span>Price<span>' + ele.Price + '</span>');
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#makeMeScrollable");
});
}