I have a few problem with my script:
it does not attach the click function to new elements
does not load elements that have inline java in them
My goal is to make a website with live page changes and a slide right-left method on click function while removing the # from the url.
Here's my code:
$(function(){
if (Modernizr.history) {
var newHash = "",
$mainContent = $("#main-content"),
$pageWrap = $("#page-wrap"),
baseHeight = 0,
$el;
$panel = $("#panel");
$panel.visible = false;
$pageWrap.height($pageWrap.height());
baseHeight = $pageWrap.height() - $mainContent.height();
$("li").delegate("a", "click", function () {
_link = $(this).attr("href");
history.pushState(null, null, _link);
ajaxcontent();
loadContent(_link);
return false;
});
function ajaxcontent(href) {
var content = $('#guts' + href).html();
$("#page-wrap").stop().css("position", "relative").animate({
left: "3000px"
}, 1000, 'easeOutSine', function () {});
}
function loadContent(href) {
$mainContent.find("#guts").fadeOut(200, function () {
$mainContent.load(href + " #guts", function () {
$mainContent.fadeIn(200, function () {
$pageWrap.animate({
height: baseHeight + $mainContent.height() + "px"
});
jQuery("#page-wrap").css({
display: "block",
left: "-3000px"
}).animate({
left: "0px"
}, 1000, 'easeOutSine');
});
$("li a[href*='+href+']").removeClass("current");
console.log(href);
$("li a[href*='+href+']").addClass("current");
});
});
}
$(document).bind('popstate', 'guts', function (e, data) {
_link = location.pathname.replace(/^.*[\\\/]/, ''); //get filename only
loadContent(_link);
});
} // otherwise, history is not supported, so nothing fancy here.
});
this is the head located on the file im including
<script type="text/javascript">
var CCM_DISPATCHER_FILENAME = '/get-installed-today/index.php';
var CCM_CID = 144;
var CCM_EDIT_MODE = false;
var CCM_ARRANGE_MODE = false;
var CCM_IMAGE_PATH = "/get-installed-today/concrete/images";
var CCM_TOOLS_PATH = "/get-installed-today/index.php/tools/required";
var CCM_BASE_URL = "http://dralarm.net";
var CCM_REL = "/get-installed-today";
</script>
<link rel="stylesheet" type="text/css" href="/get-installed- today/concrete/css/ccm.base.css?v=70f0a7a04670ba4505c2723bfe639897" />
<script type="text/javascript" src="/get-installed-today/concrete/js/jquery.js?v=70f0a7a04670ba4505c2723bfe639897"></script>
<script type="text/javascript" src="/get-installed-today/concrete/js/ccm.base.js?v=70f0a7a04670ba4505c2723bfe639897"></script>
<style type="text/css">
#blockStyle562MainBodyLayout4Cell134 {background-repeat:no-repeat; margin:0 0 5px 0; padding:0 0 5px 0; }
#blockStyle979MainBodyLayout7Cell244 {background-repeat:no-repeat; margin:0 5px 5px 5px; padding:0 5px 5px 5px; }
#blockStyle1192MainBodyLayout7Cell143 {background-repeat:no-repeat; margin:0 5px 5px 5px; padding:0 5px 5px 5px; }
#blockStyle1193MainBodyLayout7Cell344 {background-repeat:no-repeat; margin:0 5px 5px 5px; padding:0 5px 5px 5px; }
#id1 {background-repeat:no-repeat; }
#ccm-layout-mainbody-248-7 .ccm-layout-col-spacing { margin:0px 5px }
#ccm-layout-mainbody-249-3 .ccm-layout-col-spacing { margin:0px 3px }
#ccm-layout-mainbody-198-10 .ccm-layout-col-spacing { margin:0px 10px }
</style>
<style type="text/css">
#blockStyle934Main63 {background-color:#ed0303; background-repeat:repeat-x; }
</style>
<style type="text/css">
#blockStyle1190Main64 {background-image: url('/get-installed- today/files/5213/7022/9692/sidebar-red270.png'); background-repeat:repeat-x; }
</style>
<link rel="stylesheet" type="text/css" href="/get-installed-today/concrete/blocks/form/view.css?v=70f0a7a04670ba4505c2723bfe639897" />
<link rel="stylesheet" type="text/css" href="/get-installed-today/concrete/blocks/slideshow/view.css?v=70f0a7a04670ba4505c2723bfe639897" />
here is the body
<div id="ccm-layout-wrapper-4786" class="ccm-layout-wrapper">
<div id="ccm-layout-mainbody-69-4" class="ccm-layout ccm-layout-table ccm-layout-name-MainBody-Layout-4 ">
<div class="ccm-layout-row ccm-layout-row-1"><div class="ccm-layout-69-col-1 ccm-layout-cell ccm-layout-col ccm-layout-col-1 first" style="width:100%"> <div id="blockStyle562MainBodyLayout4Cell134" class=" ccm-block-styles" >
<script type="text/javascript">
//<![CDATA[
var ccmSlideShowHelper562 = {
bID:562,
imgNum:0,
init:function(){
this.displayWrap=$('#ccm-SlideshowBlock-display'+this.bID);
if(this.imgInfos.length==0){
//alert('There are no images in this slideshow');
return false;
}
var maxHeight=0;
for(var i=0;i<this.imgInfos.length;i++){
this.addImg(i);
if(maxHeight==0 || this.imgInfos[i].imgHeight > maxHeight)
maxHeight=this.imgInfos[i].imgHeight;
}
this.displayWrap.css('height',maxHeight);
//center images
for(var i=0;i<this.imgInfos.length;i++){
if( this.imgInfos[i].imgHeight < maxHeight){
var t=((maxHeight - this.imgInfos[i].imgHeight)/2);
this.imgEls[i].css('top',t);
}
}
this.nextImg();
},
nextImg:function(){
if(this.imgNum>=this.imgInfos.length) this.imgNum=0;
this.imgEls[this.imgNum].css('opacity',0);
this.imgEls[this.imgNum].css('display','block');
this.imgEls[this.imgNum].animate({opacity:1},
this.imgInfos[this.imgNum].fadeDuration*1000,'',function(){ccmSlideShowHelper562.preparefadeOut()});
var prevNum=this.imgNum-1;
if(prevNum<0) prevNum=this.imgInfos.length-1;
if(this.imgInfos.length==1) return;
this.imgEls[prevNum].animate({opacity:0},this.imgInfos[this.imgNum].fadeDuration*800,function(){this.style.zIndex=1;});
},
preparefadeOut:function(){
if(this.imgInfos.length==1) return;
var milisecDuration=parseInt(this.imgInfos[this.imgNum].duration)*1000;
this.imgEls[this.imgNum].css('z-index',2);
setTimeout('ccmSlideShowHelper'+562+'.nextImg();',milisecDuration);
this.imgNum++;
},
maxHeight:0,
imgEls:[],
addImg:function(num){
var el=document.createElement('div');
el.id="slideImgWrap"+num;
el.className="slideImgWrap";
if(this.imgInfos[num].fullFilePath.length>0)
imgURL=this.imgInfos[num].fullFilePath;
else imgURL='/get-installed-today/files/'+this.imgInfos[num].fileName;
//el.innerHTML='<img src="'+imgURL+'" >';
el.innerHTML='<div style="height:'+this.imgInfos[num].imgHeight+'px; background:url(\''+escape(imgURL)+'\') center no-repeat"> </div>';
//alert(imgURL);
if(this.imgInfos[num].url.length>0) {
//el.linkURL=this.imgInfos[num].url;
var clickEvent='onclick="return ccmSlideShowHelper562.imgClick( this.href );"';
el.innerHTML='<a href="'+this.imgInfos[num].url+'" '+clickEvent+' >'+el.innerHTML+'</a>';
}
el.style.display='none';
this.displayWrap.append(el);
var jqEl=$(el);
this.imgEls.push(jqEl);
},
imgClick:function(linkURL){
//override for custom behavior
},
imgInfos:[
{
fileName:"home-security-02.jpg",
fullFilePath:"/get-installed-today/files/8013/6798/3067/home-security-02.jpg",
duration:5,
fadeDuration:2,
url:"",
groupSet:0,
imgHeight:300 }
, {
fileName:"protect-04-1.png",
fullFilePath:"/get-installed-today/files/3413/6796/1826/protect-04-1.png",
duration:5,
fadeDuration:2,
url:"",
groupSet:0,
imgHeight:278 }
, {
fileName:"home-security.jpg",
fullFilePath:"/get-installed-today/files/9213/6796/1210/home-security.jpg",
duration:5,
fadeDuration:2,
url:"",
groupSet:0,
imgHeight:300 }
]
}
$(function(){ccmSlideShowHelper562.init();});
//]]>
</script>
<div id="ccm-SlideshowBlock-display562" class="ccm-SlideshowBlock-display">
<div id="ccm-SlideshowBlock-heightSetter562" class="ccm-SlideshowBlock-heightSetter"> </div>
<div class="ccm-SlideshowBlock-clear" ></div>
</div>
</div></div>
this is a slide show built by concrete 5
Use jQuery .live() to bind actions on javascript generated/created content.
For example:
$('#some_new_item').live('click', function() {
console.log('Hey, stop poking!');
});
Related
I create a button, then the button is supposed to triggered a JS function that will call another JS function. I tried to put Alert function in JS to test if it triggered, but it didn't. Anyone can help me?
Why it didn't get triggered?
$(document).ready(function() {
$("#btnProcess3").attr("disabled", "disabled");
alert("hi")
jsProcess(0);
$("#btnProcess3").click(function() {
alert("hi")
$(this).attr("disabled", "disabled");
jsProcess(1);
});
});
function jsProcess(action) {
var page;
var sDate;
var sBizDate;
sDate = $('#txtDate').val();
if ($('#chkuseBizDate').is(':checked')) {
sBizDate = $('#txtBizDate').val();
} else {
sBizDate = sDate;
}
page = "LoadPPSFile_details01.asp?TaskId=<%=sTaskId %>&txtDate=" + (sDate) + "&RunProcess=" + action + "&txtBizDate=" + (sBizDate);
document.getElementById("IProcess").src = page;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<input type="button" name="btnProcess" id="btnProcess3" value="Start - Services" width="250" style="VISIBILITY:show; WIDTH: 150px; HEIGHT: 22px; Background-Color:#1E90FF; Border-Color:white; Color:white; Font-Weight:bold;Font-family:Verdana;Cursor:hand; "
/>
Your code is missing some code that the jsProcess() is looking for, but the Button performs as excepted, when you remove the Disabling part.
$(document).ready(function() {
// $("#btnProcess3").attr("disabled", "disabled");
// alert("hi")
// jsProcess(0);
$("#btnProcess3").click(function() {
alert("I'm triggered!")
$(this).attr("disabled", "disabled");
// jsProcess(1);
});
});
function jsProcess(action) {
var page;
var sDate;
var sBizDate;
sDate = $('#txtDate').val();
if ($('#chkuseBizDate').is(':checked')) {
sBizDate = $('#txtBizDate').val();
} else {
sBizDate = sDate;
}
page = "LoadPPSFile_details01.asp?TaskId=<%=sTaskId %>&txtDate=" + (sDate) + "&RunProcess=" + action + "&txtBizDate=" + (sBizDate);
document.getElementById("IProcess").src = page;
}
#btnProcess3 {
VISIBILITY: show;
WIDTH: 150px;
HEIGHT: 22px;
Background-Color: #1E90FF;
Border-Color: white;
Color: white;
Font-Weight: bold;
Font-family: Verdana;
Cursor: hand;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<input type="button" name="btnProcess" id="btnProcess3" value="Start - Services" width="250">
$(document).ready(function() {
var hero_image = new Array();
hero_image[0] = new Image();
hero_image[0].src = 'assets/images/link.png';
hero_image[0].id = 'image';
hero_image[1] = new Image();
hero_image[1].src = 'assets/images/bongo.png';
hero_image[1].id = 'image';
hero_image[2] = new Image();
hero_image[2].src = 'assets/images/gandondorf.jpg';
hero_image[2].id = 'image';
hero_image[3] = new Image();
hero_image[3].src = 'assets/images/queen.png';
hero_image[3].id = 'image';
var young_hero = ["Link", "Bongo Bongo", "Gandondorf", "Queen Gohma"];
var health = [100, 70, 120, 50];
var attack_power = [];
var counter_power = [];
console.log(hero_image[0]);
function it_is_over_9000(){
for (var i = 0; i < young_hero.length; i++) {
var x = Math.floor(Math.random(attack_power)*20) + 3;
var y = Math.floor(Math.random(attack_power)*10) + 3;
attack_power.push(x);
counter_power.push(y);
}
}
function ready_board(){
it_is_over_9000();
for (var i = 0; i < young_hero.length; i++) {
var hero_btns = $("<button>");
hero_btns.addClass("hero hero_button");
hero_btns.attr({
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
hero_btns.text(young_hero[i]);
hero_btns.append(hero_image[i]);
hero_btns.append(health[i]);
$("#buttons").append(hero_btns);
}
}
function char(){
$(".hero_button").on("click", function() {
var hero = $(this);
var hero_select = hero.data('index');
for (var i = 0; i < young_hero.length; i++) {
//var attack = ;
if (i != hero_select){
var enemies = $("<button>");
enemies.addClass("hero enemy");
enemies.attr({
"data-power" : it_is_over_9000(),
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
enemies.text(young_hero[i]);
enemies.append(hero_image[i]);
enemies.append(health[i]);
$("#battle").append(enemies);
}
}
$("#buttons").html($(this).data('name','health','image'));
defender();
});
}
function defender(){
$(".enemy").on("click", function() {
var enemy = $(this);
var enemy_select = enemy.data("index");
console.log(enemy_select);
for (var i = 0; i < young_hero.length; i++) {
if (i == enemy_select) {
var defender = $("<button>");
defender.addClass("hero defender");
defender.attr({
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
defender.text(young_hero[i]);
defender.append(hero_image[i]);
defender.append(health[i]);
$("#defend").append(defender);
$(this).remove();
}
}
});
}
$(".defend_button").on("click" , function(){
if($(".defender").data("health") == 0){
$(".defender").remove();
}
$(".defender").attr({
"data-health": $(".defender").data("health") - $(".hero_button").data("attack")
});
});
ready_board();
char();
});
I am trying to make a RPG game and I have the characters being generated the way I want them too but on the $(".defend_button").on("click" , function() at the end it doesn't update the data-health as it should. It only updates once but upon many clicks on the defend-button it doesn't update past the first time.
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Zelda</title>
<script type='text/javascript' src='https://code.jquery.com/jquery-2.2.0.min.js'></script>
<script type = "text/javascript" src = "assets/javascript/game.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
</head>
<style type="text/css">
.hero { width: 125px; height:150px; border-style: solid; padding: 2px; float: left; margin: 2px; float: left; }
.letter-button-color { color: darkcyan; }
.fridge-color { color: orange; }
#display { margin-top:78px; height:500px; width:220px; margin-left:60px; }
#buttons { padding-top:60px; }
#clear { margin-left: 20px; font-size: 25px; color: black; border-style: solid; width: 100px; }
#image{width: 100px; height: 100px; margin-left: 10px; }
</style>
<body>
<div class="row">
<div class="col-md-8">Select Your Character</div>
</div>
<div class="row">
<div id="buttons" class="col-md-8"></div>
</div>
<div class="row">
<div id="battle" class="col-md-8">
</div>
</div>
<div class="row">
<div class="col-md-8">
<button class="btn btn-primary defend_button">Defend</button>
</div>
</div>
<div class="row">
<div id="defend">
</div>
</div>
</body>
</html>
You have to use .data() to update the health value.
var battleResult = $(".defender").data("health") - $(".hero_button").data("attack");
console.log("battleResult should be: "+battleResult );
$(".defender").data({
"health": battleResult
});
I played a little with your game.
I found how to update the health display below the image too...
Since only updating the data wasn't changing anything on the screen.
So, I left the above code there, for you to see it is effectively working.
But since you have to re-create the button to update health on scrreen... It is kind of useless.
I also fixed the death condition
from if($(".defender").data("health") == 0){
to if($(".defender").data("health") <= 0){
I have to stop here before changing to much things.
See it in CodePen
Check your loop in it_is_over_9000(), because I think it is running uselessly too often.
And a dead defender has to be "buried" (lol).
Because when it is killed, a click on the defend button is kind of ressurrecting it.
;)
Try setting the attribute like this. Also, I recommend putting $(".defender") in a variable so you aren't requerying it each time.
var defender = $(".defender");
var loweredHealth = defender.data("health") - $(".hero_button").data("attack");
defender.attr('data-health`, loweredHealth);
Update:
It looks like the $('.defender') call will return multiple items. You either need to select a specific defender or iterate through them individually like so:
$('.defender').each(function(i, nextDefender) {
var loweredHealth = nextDefender.data("health") - $(".hero_button").data("attack");
nextDefender.attr('data-health`, loweredHealth);
});`
I'm having trouble getting the id of the outer div the draggable element is being taken from.
Here is my HTML
http://dev.eteacher.online/taskAssets/cup.jpg'/>
///Droppables ".snap"
<div id="0" class='col-word'><p class="letters">c</p></div>
<div id="1" class='col-word snap' style=""><p class="letters">__</p></div>
<div id="2" class='col-word snap' style=""><p class="letters">__</p></div>
///Draggables
<div id="comparison">
<div id="v" class='col-letter'><p class="letters">v</p></div>
<div id="p" class='col-letter'><p class="letters">p</p></div>
<div id="u" class='col-letter'><p class="letters">u</p></div>
</div>
Then I have the important jQuery
var beh = new Array();
var beh2 = "";
var MyVar = "";
$(".col-letter").draggable({ cursor: 'move', snap: '.snap',
revert : function(event, ui) {
// on older version of jQuery use "draggable"
// $(this).data("draggable")
// on 2.x versions of jQuery use "ui-draggable"
// $(this).data("ui-draggable")
$(this).data("ui-draggable").originalPosition = {
top : 0,
left : 0
};
// return boolean
return !event;
// that evaluate like this:
// return event !== false ? false : true;
},
drag: function(event, ui){
if($(this).data('droppedin')){
$(this).data('droppedin').droppable('enable');
$(this).data('droppedin',null);
$(this).removeClass( 'dropped' );
MyVar = $(this).closest(".col-word").attr("id");
alert(MyVar);
beh[MyVar] = "";
alert(beh);
}
}
});
$(".snap").droppable({
hoverClass: 'hovered',
tolerance: 'pointer',
drop: function(event, ui) {
var drop_p = $(this).offset();
var drag_p = ui.draggable.offset();
var left_end = drop_p.left - drag_p.left;
var top_end = drop_p.top - drag_p.top ;
ui.draggable.animate({
top: '+=' + top_end,
left: '+=' + left_end
});
ui.draggable.addClass( 'dropped' );
ui.draggable.data('droppedin',$(this));
$(this).droppable('disable');
}
});
$( ".snap" ).on( "drop", function( event, ui ) {
MyVar = $(this).parent().attr('id');
beh[MyVar] = ui.draggable.attr('id');
alert(beh[MyVar] + " " + MyVar);
// alert(beh);
//beh[] = new Array($(this).attr('id'), ui.draggable.attr('id'));
//alert(beh);
});
Basically you can drag divs in and out of the .snap class. I want to get the id of the .snap class when I drag the divs off of the .snap.
I'm having trouble doing this. The closest function is bringing me undefined!
Any ideas?
EDIT Goal: The goal is to know which id for each col-letter gets placed on which .snap class.
The way to I thought it out was to have a get request once a button is pressed such that the position and the letter are provided.
For example, if you place id=v on id=1. the get request will enable /1v.
EDIT 2
This worked!
$(".snap").on("drop", function(event, ui) {
MyVar = ui.helper.attr('id');
beh[MyVar] = $(this).attr('id') + ui.helper.attr('id');
alert(beh[MyVar]);
});
But it makes my join command stop working!
$( "#done" ).click(function(){
beh2 = beh.join("");
var link = "/task/fillLetters/response/"+ beh2;
alert(beh2);
window.location.replace(link);
});
Any ideas?
I think this is what you need
fiddle link https://jsfiddle.net/bksL352s/
var beh = new Array();
var beh2 = "";
var MyVar = "";
$(".col-letter").draggable({
cursor: 'move',
snap: '.snap',
revert: function(event, ui) {
$(this).data("ui-draggable").originalPosition = {
top: 0,
left: 0
};
return !event;
},
drag: function(event, ui) {
if ($(this).data('droppedin')) {
$(this).data('droppedin').droppable('enable');
$(this).data('droppedin', null);
$(this).removeClass('dropped');
MyVar = $(this).attr('data-dropped-Id');
alert(MyVar);
beh[MyVar] = "";
alert(beh);
}
}
});
$(".snap").droppable({
hoverClass: 'hovered',
tolerance: 'pointer',
drop: function(event, ui) {
var drop_p = $(this).offset();
var drag_p = ui.draggable.offset();
var left_end = drop_p.left - drag_p.left;
var top_end = drop_p.top - drag_p.top;
ui.draggable.animate({
top: '+=' + top_end,
left: '+=' + left_end
});
ui.draggable.addClass('dropped');
ui.draggable.data('droppedin', $(this));
$(this).droppable('disable');
}
});
$(".snap").on("drop", function(event, ui) {
MyVar = event.target.getAttribute('id');
beh[MyVar] = ui.draggable.attr('id');
ui.draggable.attr('data-dropped-Id', $(this).attr('id'));
alert(beh[MyVar] + " " + MyVar);
});
.col-letter {
display: inline-block;
border: 1px solid #ccc;
background: #eee;
margin: 10px 0;
transition: background ease-In .2s;
}
.col-word.snap {
display: inline-block;
border: 1px solid #000;
background: #C5C5C5;
}
.dropped p {
background: #CDDC39 !important;
}
.dropped {
border-color: #000 !important;
}
.col-word.snap p {
margin: 0;
padding: 5px;
width: 30px;
height: 30px;
text-align: center;
line-height: 1.5;
}
.col-letter p {
margin: 0;
padding: 5px;
width: 30px;
height: 30px;
text-align: center;
line-height: 1.5;
cursor: move;
}
<link href="https://code.jquery.com/ui/1.11.4/themes/black-tie/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<div id="0" class='col-word'>
<p class="letters">c</p>
</div>
<div id="1" class='col-word snap' style="">
<p class="letters">__</p>
</div>
<div id="2" class='col-word snap' style="">
<p class="letters">__</p>
</div>
<div id="comparison">
<div id="v" class='col-letter'>
<p class="letters">v</p>
</div>
<div id="p" class='col-letter'>
<p class="letters">p</p>
</div>
<div id="u" class='col-letter'>
<p class="letters">u</p>
</div>
</div>
Hope this helps..:)
The following will get you the id of both the dragged element and dropped element..
$(".snap").on("drop", function(event, ui) {
MyVar = $(this).attr('id');
beh[MyVar] = ui.helper.attr('id');
alert(MyVar + " " + beh[MyVar]);
});
Same goes with your drag function use
MyVar = $(this).attr('id'); //to get your id
Fiddle
https://jsfiddle.net/2a6tur6w/3/
You are after event.target in your 'drop' handler...
$(".snap").on("drop", function(event, ui) {
MyVar = $(event.target).attr('id'); // here
beh[MyVar] = ui.draggable.attr('id');
alert(beh[MyVar] + " " + MyVar);
});
fiddle: https://jsfiddle.net/zoa3wL0n/
Why can't you store the value with the onclick handler and then retrieve it when you 'drop'?
var draggedItem
$(".snap").on("drag", function(event, ui) {
draggedItem = $(this).attr('id');
});
$(".snap").on("drop", function(event, ui) {
alert(draggedItem)
});
i want to take input from user(number) and display image as many times as number.If user inputs 5 then the image should be displayed 5 times next to each other with corresponding number below the images-Below 1st image '1' 2nd Image '2'.Basically putting this table in loop.
<HTML>
<BODY>
<TABLE>
<TR>
<TD>
<IMG SRC="C:/Users/User/Desktop/RE/G.JPG">
</TD>
</TR>
<TR><TD ALIGN="CENTER">1</TD>
</TABLE>"
</BODY>
</HTML>
You can use jQuery for this task and write a function that generates HTML with a dynamic value:
Complete Solution
<HTML>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function generateTable(number) {
return "<table><tr><td>" +
"<img src='C:/Users/User/Desktop/RE/G.JPG'></td></tr><tr><td align='center'>" +
number +
"</td></table>";
}
$(function(){
var userInput = 3;
for (var i = 0; i < userInput; i++) {
$('#dynamic').append(generateTable(i + 1));
}
});
</script>
</head>
<body>
<div id='dynamic'></div>
</body>
</html>
You can add an input and a button to trigger the function.
You could also check if the inserted value is actually a number or not.
$(document).on('click', '#add', function() {
var that = $(this);
var times = parseInt($('#times').val());
for (i=1;i<=times;i++) {
$('#table-wrp').append('<table class="table-times"><tbody><tr><td><img src="http://code52.org/aspnet-internationalization/icon.png" /></td></tr><tr><td>' + i + '</td></tr></tbody></table>');
}
});
$(document).on('input', '#times', function() {
var that = $(this);
var value = that.val();
if ((value != '' || value != false) && !isNaN(value)) {
$('#add').prop('disabled', false);
} else {
$('#add').prop('disabled', true);
}
});
#table-wrp {
height: 80px;
}
.table-times {
width: 100px;
height: 80px;
float: left;
border-collapse: collapse;
}
.table-times td {
border: 1px solid #d8d8d8;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="textbox" id="times" />
<button id="add" disabled>Add</button>
<div id="table-wrp"></div>
Or for a pure javascript version of Pugazh's answer
var tab = "<div></div>";
var num = prompt("Enter a number");
for(i = 0; i < num; i++){
document.getElementById('tab').innerHTML += "<div><div><img src='http://placehold.it/150x150'></div><div></div></div>";
}
img{
float: left;
box-shadow: 5px 5px 10px rgba(0,0,0,0.4);
height: 100px;
width: 100px;
margin: 10px;
}
<div id="tab"></div>
This will work just as well, but doesn't require jQuery as well.
<HTML>
<BODY>
<div id="tbl"></div>
</BODY>
</HTML>
<script>
var num = prompt("Enter a number");
var div=document.getElementById("tbl");
var l1='',l2="";
for(i=0;i<num;i++)
{
l1 += '<td><img src="C:/Users/User/Desktop/RE/G.JPG"></td>';
l2 += '<td>'+i+'</td>';
}
div.innerHTML = "<table><tr>"+l1+"</tr><tr>" + l2 + "</tr></table>";
</script>
Try this
$(function() {
var tab = "<div></div>";
var num = prompt("Enter a number");
for (i = 0; i < num; i++) {
$("#tab").append("<div class='left'><div><img src='http://placehold.it/150x150'></div><div>" + (i + 1) + "</div></div>");
}
});
div.left {
display: inline-block;
margin-right: 5px;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="tab">
</div>
</body>
</html>
I have dynamically created textareas which are nested in a dynamcally created divs. the divs are draggabnle and the textareas are resizable using jquery.
I want the border and drag/resize handles for any paticular div/textarea to only appear when the user clicks on that paticular textarea. I am assuming I would need to use the same onclick event that the draggable is using but I dont have the js knowledge for making the handles and border show up.
any help greatly appreciated
here is my code
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<head>
<style>
body{background-color:#ccc;}
.dragbox{width:10px; height:10px;padding: 0.0em; margin:25px; border:0;cursor:move; z-index:2}
.textarea1{ width: 300px; height: 300px; padding: 0.5em; z-index:3}
#handle{
display: block;
height: 16px;
width: 100px;
background-color: red;
position: absolute;
top:-15px;
left:0px;
font-size:10px;
}
#content
{
position:absolute;
top:150px;
left:0px;
margin:auto;
z-index:1;
}
</style>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />
<script src = "http://js.nicedit.com/nicEdit-latest.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<script>
var i=0;
var p=25;
}
function editor1(idf) {
//var body = document.body;
// The magic
document.getElementById(idf).addEventListener ("dblclick", function (event) {
var target = event.target;
if (target.nodeName === "TEXTAREA") {
var area = new nicEditor ({fullPanel : true}).panelInstance (target);
area.addEvent ("blur", function () {
this.removeInstance (target);
});
}
}, false);
};
function NewTextArea(id)
{
id=id+i;
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
newdiv.setAttribute('class', 'dragbox');
newdiv.setAttribute('iterate',i);
newdiv.style.position = "relative";
newdiv.style.top = p;
newdiv.style.left = p;
newdiv.style.cursor='move';
newdiv.innerHTML = "<div id='handle'>Drag me into position</div></div><br><textarea id='"+i +"' onDblClick='editor1("+i+")' name='textarea["+i +"]' class='textarea1' style='position:absolute; top:0px;left:0px;overflow-y: auto;background-color:transparent;border: 2px dashed #000; '>some text here</textarea>";
newdiv.innerHTML=newdiv.innerHTML+"<br><input type='hidden' value='"+i+"' name='id["+i+"]'><br><input name='box_type["+i+"]' type='hidden' value='text'/>";
newdiv.innerHTML=newdiv.innerHTML+"<br><input type='hidden' value='300' name='width["+i+"]' id='width"+i+"'><br><input type='hidden' value='300' name='height["+i+"]' id='height"+i+"'>";
newdiv.innerHTML=newdiv.innerHTML+"<br><input type='hidden' value='0' name='left["+i+"]' id='left"+i+"'><br><input type='hidden' value='0' name='top["+i+"]' id='top"+i+"'>";
document.getElementById("frmMain").appendChild(newdiv);
$(function()
{
$("#"+i).resizable(
{
stop: function(event, ui)
{
var width = ui.size.width;
var height = ui.size.height;
// alert("width="+width+"height="+height);
ValProportions(width,height,ui.element.context.id);
}
});
$( "#"+id ).draggable(
{
stop: function(event, ui)
{
Stoppos = $(this).position();
$("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top);
// alert("left="+Stoppos.left+"top="+Stoppos.top);
ValPostion(Stoppos.left,Stoppos.top,$(this).attr('iterate'));
}
});
$("#"+i).draggable({handle:"#handle"});
});
function ValProportions(defaultwidth, defaultheight,id) {
$('#width'+id).val(defaultwidth);
$('#height'+id).val(defaultheight);
}
function ValPostion(defaultleft,defaulttop,id) {
$('#left'+id).val(defaultleft);
$('#top'+id).val(defaulttop);
}
i++;
p=p+25;
}
</script>
</head>
<body>
<form id="frmMain" name="frmMain" enctype="multipart/form-data" action="dynamic_div5.php" method="post">
<input id="btn1" type="button" value="Add New textbox" onClick="NewTextArea('draggable');"/>
<input type="submit" value="Save Page" >
</form>
</body>
</html>
If I understand the question correctly, this can be done with just CSS:
textarea { resize:none; border:none; }
textarea:focus { resize:both; border:1px solid #000; }
JSFiddle example.