show borders and handles on textarea when highlighted - javascript

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.

Related

jQuery - hover works only on every 2nd div

I have a problem. I'm creating a divs from input form, but when I hover my mouse with .hover function, it works only on every second div element (first, third, 5th, 7th...). How do I solve that? What's wrong with JS function?
Thanks for answers.
JS:
$("#entryButton").click(function(){
event.preventDefault(); //stops refreshing
var query = $("#entry").val(); //string z inputa
if (query !== "") {
var trashButton = "<button class='trash'>DEL</button>"
var registry = "<div class='drag'>" + "<p>" + query + "</p>" + trashButton + "</div>"
$("#list").append(registry); //add div with query and ubbton
$("#list").sortable({
//axis: "y",
});
$(".drag").hover(function() {
$(this).toggleClass("mousehover")
});
$("#entry").val(""); //clear value
return false; //also stops refreshing
console.log(registry);
}
})
HTML:
<div class="container">
<form>
<input type="text" id="entry">
<button id="entryButton">button</button>
</form>
<ul id="list">
</ul>
</div>
CSS:
body {
font-size: 14px;
}
form {
float:right;
}
.container {
min-width:300px;
width:20%;
margin: 0 auto;
margin-top:5px;
}
.drag {
margin-top:5px;
background-color:lemonchiffon;
display:inline-flex;
width:100%;
}
.trash {
position:absolute;
margin-left:190px;
}
.mousehover {
opacity:0.5;
}
The problem is that you are adding the hover event multiple times. It is better to do it only once, using $(document).on().
$("#entryButton").click(function(){
event.preventDefault(); //stops refreshing
var query = $("#entry").val(); //string z inputa
if (query !== "") {
var trashButton = "<button class='trash'>DEL</button>"
var registry = "<div class='drag'>" + "<p>" + query + "</p>" + trashButton + "</div>"
$("#list").append(registry); //add div with query and ubbton
$("#list").sortable({
//axis: "y",
});
$("#entry").val(""); //clear value
return false; //also stops refreshing
console.log(registry);
}
});
$(document).on("mouseenter mouseleave", ".drag", function() {
$(this).toggleClass("mousehover");
});
body {
font-size: 14px;
}
form {
float:right;
}
.container {
min-width:300px;
width:20%;
margin: 0 auto;
margin-top:5px;
}
.drag {
margin-top:5px;
background-color:lemonchiffon;
display:inline-flex;
width:100%;
}
.trash {
position:absolute;
margin-left:190px;
}
.mousehover {
opacity:0.5;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="container">
<form>
<input type="text" id="entry">
<button id="entryButton">button</button>
</form>
<ul id="list">
</ul>
</div>
Here you go with a solution https://jsfiddle.net/wcu4w1mn/
$("#entryButton").click(function(){
event.preventDefault(); //stops refreshing
var query = $("#entry").val(); //string z inputa
if (query !== "") {
var trashButton = "<button class='trash'>DEL</button>"
var registry = "<div class='drag'>" + "<p>" + query + "</p>" + trashButton + "</div>"
$("#list").append(registry); //add div with query and ubbton
$("#list").sortable({
//axis: "y",
});
$(".drag").last().hover(function() {
$(this).toggleClass("mousehover")
});
$("#entry").val(""); //clear value
return false; //also stops refreshing
console.log(registry);
}
})
body {
font-size: 14px;
}
form {
float:right;
}
.container {
min-width:300px;
width:20%;
margin: 0 auto;
margin-top:5px;
}
.drag {
margin-top:5px;
background-color:lemonchiffon;
display:inline-flex;
width:100%;
}
.trash {
position:absolute;
margin-left:190px;
}
.mousehover {
opacity:0.5;
}
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="container">
<form>
<input type="text" id="entry">
<button id="entryButton">button</button>
</form>
<ul id="list">
</ul>
</div>
Only changed code
Add hover event to only last added element.
$(".drag").last().hover(function() {
$(this).toggleClass("mousehover")
});
Hope this will help you.

Canvas drawing getting blur

Somehow the canvas drawing is getting blur when attached under tabs of jquery ui.
Can anybody help me to figure out why canvas drawing is getting blur?
problem seems to be in this section
.ui-tabs-panel {
height:500px; }
#chartCanvas-1,#crossCanvas-1{
position:absolute; top:50px; left:0px;
/*border:1px solid blue;
width:500px;
height:400px;*/
}
/*#crossCanvas-1{ border:1.5px solid green;}
#chartCanvas-1{ border:1px solid red;}*/
Using jquery 1.8.3
Using jquery ui and css
<html lang="en">
<head>
<meta charset="utf-8" />
<title> Create dynamic Tabs using jQuery and css</title>
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript" src="jquery-ui.js"></script>
<script type="text/javascript" language="javascript">
$(function() {
var tabTitle = $( "#tab_title" ),
tabContent = $( "#tab_content" ),
tabTemplate = "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>",
tabCounter = 2;
var tabs = $( "#tabs" ).tabs();
// modal dialog init: custom buttons and a "close" callback reseting the form inside
var dialog = $( "#dialog" ).dialog({
autoOpen: false,
modal: true,
buttons: {
Add: function() {
addTab();
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
}
});
// addTab form: calls addTab function on submit and closes the dialog
var form = dialog.find( "form" ).submit(function( event ) {
addTab();
dialog.dialog( "close" );
event.preventDefault();
});
// actual addTab function: adds new tab using the input from the form above
function addTab() {
var label = tabTitle.val() || "Tab " + tabCounter,
id = "tabs-" + tabCounter,
chartCanvas_id = "chartCanvas-" + tabCounter,
crossCanvas_id = "crossCanvas-" + tabCounter,
li = $( tabTemplate.replace( /#\{href\}/g, "#" + id ).replace( /#\{label\}/g, label ) ),
tabContentHtml = tabContent.val() || "Tab " + tabCounter + " content.";
tabs.find( ".ui-tabs-nav" ).append( li );
tabs.append( "<div id='" + id + "'><canvas id='"+chartCanvas_id+ "'></canvas><canvas id='"+crossCanvas_id+ "'></canvas></div>" );
tabs.tabs( "refresh" );
tabCounter++;
}
// addTab button: just opens the dialog
$( "#add_tab" )
.button()
.click(function() {
dialog.dialog( "open" );
});
// close icon: removing the tab on click
$( "#tabs span.ui-icon-close" ).live( "click", function() {
var panelId = $( this ).closest( "li" ).attr( "aria-controls" );
if( panelId !== "tabs-1")
{
panelId = $( this ).closest( "li" ).remove().attr( "aria-controls" );
$( "#" + panelId ).remove();
tabs.tabs( "refresh" );
}
});
var canvas=document.getElementById("chartCanvas-1");
var context=canvas.getContext("2d");
var canvasOffset=$("#chartCanvas-1").offset();
/*var canvasTemp=document.getElementById("crossCanvas-1");
var ctxTemp=canvasTemp.getContext("2d");
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;*/
context.beginPath();
context.moveTo(10, 10);
context.lineTo(40,30);
context.stroke();
context.closePath();
/*ctxTemp.beginPath();
ctxTemp.moveTo(0, 0);
ctxTemp.lineTo(40,50);
ctxTemp.stroke();
ctxTemp.closePath(); */
});
</script>
<link rel="stylesheet" href="jquery-ui.css">
<style type="text/css">
#dialog label, #dialog input { display:block; }
#dialog label { margin-top: 0.5em; }
#dialog input, #dialog textarea { width: 95%; }
#tabs { margin-top: 0.7em; height: 600px;}
#tabs li .ui-icon-close { float: left; margin: 0.4em 0.2em 0 0; cursor: pointer; }
#add_tab { cursor: pointer; }
.ui-tabs-panel {
height:500px; }
#chartCanvas-1,#crossCanvas-1{
position:absolute; top:50px; left:0px;
/*border:1px solid blue;
width:500px;
height:400px;*/
}
/*#crossCanvas-1{ border:1.5px solid green;}
#chartCanvas-1{ border:1px solid red;}*/
</style>
</head>
<body>
<div id="dialog" title="Tab data">
<form>
<fieldset class="ui-helper-reset">
<label for="tab_title">Title</label>
<input type="text" name="tab_title" id="tab_title" value="" class="ui-widget-content ui-corner-all" />
<label for="tab_content">Content</label>
<textarea name="tab_content" id="tab_content" class="ui-widget-content ui-corner-all"></textarea>
</fieldset>
</form>
</div>
<button id="add_tab">Add Tab</button>
<div id="tabs">
<ul>
<li>Default <span class="ui-icon ui-icon-close">Remove Tab</span></li>
</ul>
<div id="tabs-1">
<canvas id="chartCanvas-1" style="width: 600px; height: 400px"></canvas>
<!-- <canvas id="crossCanvas-1" style="width: 600px; height: 400px"></canvas> -->
</div>
</div>
</body>
</html>
Regards,
SK
the reson it's blurred is becuase of your CSS for the canvas, in the canvas tag.
<canvas id="chartCanvas-1" style="width: 600px; height: 400px"></canvas>
The standard size for a canvas is 300x150 pixels and changing the width and height with CSS will scale the canvas. To change the size of the canvas, instead do it in the JavaSCript code
canvas.width = 600;
canvas.height = 400;
And remove the style from your canvas tag in your HTML code
<canvas id="chartCanvas-1"></canvas>

How to dynamically create table in html with certain constraints?

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>

attaching a click function to new ajax requested data

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!');
});

Uploading Multiple Files in Salesforce through Visualforce

I would like to upload multiple files in Salesforce using visualforce.
I can upload one file at a time.
But my requirement is, i want to display only one "add a file" button in visualforce page, when clicked over that button browse window should open and user selects a particular file and adds it. But after adding a file, the file path should be displayed as well as the same "add a file" button should be displayed below that which allows us to add another file. And after that we can save what we have added. It is same as adding attachments in our email.
Any help regarding this will be appreciated.
<!-- Use uploadFile function to attach multiple attachment.Update hardcoded parent id.-->
<apex:page>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
var __sfdcSessionId = '{!GETSESSIONID()}';
var filesToUpload = [];
var uploadedFile = 0;
</script>
<style>
.FilebuttonStyle{
font-family:Arial,'Helvetica Neue',Helvetica,sans-serif;
font-size:13px`enter code here`;color:#ffffff;
background-color: #169fcc !important;
text-decoration:none;
text-align:center;
border:1px solid #1691ba !important;
line-height: 25px;!important;
border-radius:4px;
display:inline-block;
cursor:pointer;
width:85px;
}
td.fileRow {
overflow: hidden;
font-family:Arial,'Helvetica Neue',Helvetica,sans-serif;
font-size:13px;color:#ffffff;
background-color: #8db728;
text-decoration:none;
text-align:center;
border:1px solid #6c8049;
line-height: 32px;!important;
border-radius:4px;
//padding-left:10px;
//padding-right:10px;
background-image:linear-gradient(top,#9dcc3d,#7da223);
background-image:-o-linear-gradient(top,#9dcc3d,#7da223);
background-image:-moz-linear-gradient(top,#9dcc3d,#7da223);
background-image:-webkit-linear-gradient(top,#9dcc3d,#7da223);
background-image:-ms-linear-gradient(top,#9dcc3d,#7da223);
display:inline-block;
cursor:pointer;
width:120px;
overflow: hidden;
}
td.fileRow input {
display: block !important;
width: 157px !important;
height: 57px !important;
opacity: 0 !important;
overflow: hidden !important;
}
.fileCheckBox {
width: 16px;
height: 16px;
display: inline-block;
margin: 3px 5px 3px 3px;
background-color: white;
//box-shadow: 0px 0px 1px #b0b3ae;
text-align: center;
vertical-align: top;
}
.FilebuttonGroup{
float:right;
padding-right: -70px!important;
}
</style>
<script src="/soap/ajax/32.0/connection.js" type="text/javascript"></script>
<script type="text/javascript">
function uploadFile(parentId)
{
// var input = $('.fileInput')[0];
//var input = document.getElementById("file-input");
// var filesToUpload = input.files;
$("input[type=file]").each(function(){
filesToUpload.push($(this)[0].files[0]);
});
//console.log(filesToUpload);
for(var i = 0, f; f = filesToUpload[i]; i++)
{
var reader = new FileReader();
// Keep a reference to the File in the FileReader so it can be accessed in callbacks
reader.file = f;
reader.onload = function(e)
{
var att = new sforce.SObject("Attachment");
att.Name = this.file.name;
att.ContentType = this.file.type;
att.ParentId = parentId;
var binary = "";
var bytes = new Uint8Array(e.target.result);
var length = bytes.byteLength;
for (var i = 0; i < length; i++)
{
binary += String.fromCharCode(bytes[i]);
}
att.Body = (new sforce.Base64Binary(binary)).toString();
sforce.connection.create([att],
{
onSuccess : function(result, source)
{
if (result[0].getBoolean("success"))
{
console.log("new attachment created with id " + result[0].id);
}
else
{
console.log("failed to create attachment " + result[0]);
}
},
onFailure : function(error, source)
{
console.log("an error has occurred " + error);
}
});
};
reader.readAsArrayBuffer(f);
}
}
function addRow(tableID){
var row = '<tr><td><input type="checkbox" onclick="processCheckbox()" name="chk" class="fileCheckBox"/</td><td class="fileRows"><input type="file"/> </td></tr>';
$('#'+tableID).append(row);
}
function deleteRow(tableID)
{
try
{
var table=document.getElementById(tableID);
var rowCount=table.rows.length;
for(var i=0;i<rowCount;i++)
{
var row=table.rows[i];
var chkbox=row.cells[0].childNodes[0];
if(null!=chkbox&&true==chkbox.checked)
{
table.deleteRow(i);
filesToUpload.splice(i, 1);
// console.log(filesToUpload);
rowCount--;
i--;
}
}
processCheckbox();
}
catch(e)
{
alert(e);
}
}
function processCheckbox(){
$("[id$='_remove']").hide();
var checkCount=0;
$("#dataTable input[type='checkbox']").each(function(){
if($(this).is(':checked'))
{
checkCount++;
}
});
if(checkCount >0){
$("[id$='_remove']").show();
}
}
</script>
<div class="FilebuttonGroup">
<input type="button" value="Delete Row" id="_remove" onclick="deleteRow('dataTable')" class="FilebuttonStyle" title="Delete Row"/>
<input type="button" value="Add Row" onclick="addRow('dataTable')" id="_add" class="FilebuttonStyle" title="Add Row"/>
</div>
<table id="dataTable" >
<tbody>
<tr>
<td> </td>
<td class="fileRows"> <input type="file" class="fileInput"/> </td>
<td></td>
</tr>
</tbody>
</table>
<!--Correct this attachment parentid -->
<input type="button" value="Upload" onclick="uploadFile('5009000000cjeZn')" title="Upload"/>
<div id="statusid"></div>
<script>
$(document).ready(function(){
$("[id$='_remove']").hide();
$("[id$='attachmentBlock']").find('.pbSubsection').attr({'style':'margin-right:-70px !important;'});
});
</script>
</apex:page>
You can upload multiple attachment using ajax asynchronously. You need to update the parent record id of attachment. Find the code at:
https://github.com/DebGit/Dev_2015_org1/blob/master/src/pages/FileUploaderAjax.page

Categories

Resources