Drag and drop picture to text and with double click to remove the text inside the box - javascript

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8 />
<title>Basic Drag and Drop</title>
<style>
#drop {
min-height: 200px;
width: 200px;
border: 3px dashed #ccc;
margin: 10px;
padding: 10px;
clear: left;
}
p {
margin: 10px 0;
}
#triangle {
background: url(images/triangle.jpg) no-repeat;
}
#square {
background: url(images/square.gif) no-repeat;
}
#circle {
background: url(images/circle.jpg) no-repeat;
}
#red {
background: url(images/red.jpg) no-repeat;
}
#yellow {
background: url(images/yellow.jpg) no-repeat;
}
#green {
background: url(images/green.jpg) no-repeat;
}
.drag {
height: 48px;
width: 48px;
float: left;
-khtml-user-drag: element;
margin: 10px;
}
</style>
<script>
var addEvent = (function () {
if (document.addEventListener) {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.addEventListener(type, fn, false);
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
} else {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
}
})();
(function () {
var pre = document.createElement('pre');
pre.id = "view-source"
// private scope to avoid conflicts with demos
addEvent(window, 'click', function (event) {
if (event.target.hash == '#view-source') {
// event.preventDefault();
if (!document.getElementById('view-source')) {
// pre.innerHTML = ('<!DOCTYPE html>\n<html>\n' + document.documentElement.innerHTML + '\n</html>').replace(/[<>]/g, function (m) { return {'<':'<','>':'>'}[m]});
var xhr = new XMLHttpRequest();
// original source - rather than rendered source
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
pre.innerHTML = this.responseText.replace(/[<>]/g, function (m) { return {'<':'<','>':'>'}[m]});
prettyPrint();
}
};
document.body.appendChild(pre);
// really need to be sync? - I like to think so
xhr.open("GET", window.location, true);
xhr.send();
}
document.body.className = 'view-source';
var sourceTimer = setInterval(function () {
if (window.location.hash != '#view-source') {
clearInterval(sourceTimer);
document.body.className = '';
}
}, 200);
}
});
})();
</script>
<style id="jsbin-css">
</style>
</head>
<body>
<div class="drag" id="triangle" draggable="true"></div>
<div class="drag" id="square" draggable="true"></div>
<div class="drag" id="circle" draggable="true"></div>
<div class="drag" id="red" draggable="true"></div>
<div class="drag" id="yellow" draggable="true"></div>
<div class="drag" id="green" draggable="true"></div>
<div id="drop"></div>
<script>
function cancel(e) {
if (e.preventDefault) {
e.preventDefault();
}
return false;
}
var dragItems = document.querySelectorAll('[draggable=true]');
for (var i = 0; i < dragItems.length; i++) {
addEvent(dragItems[i], 'dragstart', function (event) {
// store the ID of the element, and collect it on the drop later on
event.dataTransfer.setData('Text', this.id);
});
}
var drop = document.querySelector('#drop');
// Tells the browser that we *can* drop on this target
addEvent(drop, 'dragover', cancel);
addEvent(drop, 'dragenter', cancel);
addEvent(drop, 'drop', function (e) {
if (e.preventDefault) e.preventDefault(); // stops the browser from redirecting off to the text.
this.innerHTML += '<p>' + e.dataTransfer.getData('Text') + '</p>';
return false;
});
</script>
</body>
</html>
how to double click remove the text inside the textbox by using html5? I having problem on how to remove the text out from the textbox in this html5. things can be drag and drop inside, but i want to remove the things inside that i have been dragged inside... i having problem on removing the item inside that.

Try using this.
document.getElementById('selectID').ondblclick = function(){
alert(this.selectedIndex);//remove your text here
};

Related

Get focused element on mouse cursor move using JavaScript

When I click any block it adds a new class .is-selected. It works fine when I get focus by click on the blocks. But It does not work when I use the arrow keys to get focus on another block. How can I get this focus when I use arrow keys?
let getBlocks = document.querySelectorAll(".block");
getBlocks.forEach((single) => {
single.addEventListener("focus", () => {
//remove all activated class
getBlocks.forEach((x) => {
x.classList.remove("is-selected");
});
//add the class to this new focus block
single.classList.add("is-selected");
});
});
* {
box-sizing: border-box;
}
.root {
max-width: 600px;
margin: 1rem auto;
}
.root:focus,
.block:focus {
outline: 0;
}
.is-selected {
background-color: #f4f8ff !important;
border: 1px solid #deebff !important;
}
<div class="root" contenteditable>
<p name="jYdi0" class="block" tabindex="0">1</p>
<p name="Hdy89" class="block" tabindex="0">2</p>
<p name="wEldk" class="block" tabindex="0">3</p>
</div>
UPDATED :
var ind = 0;
let getBlocks = document.querySelectorAll(".block");
function caretInfo(up = true) {
let sel = window.getSelection();
let offset = sel.focusOffset;
if (up) {
sel.modify("move", "backward", "character");
if (offset == sel.focusOffset) return true;
else {
sel.modify("move", "forward", "character");
return false;
}
} else {
sel.modify("move", "forward", "character");
if (offset == sel.focusOffset) return true;
else {
sel.modify("move", "backward", "character");
return false;
}
}
}
function selection(item) {
getBlocks.forEach((x, index) => {
if (x === item) {
ind = index;
}
x.classList.remove("is-selected");
});
//add the class to this new focus block
item.classList.add("is-selected");
}
getBlocks.forEach((item) => {
item.addEventListener('focus', () => {
selection(item);
});
});
document.addEventListener("keydown", function(event) {
let change = false;
if (event.keyCode == 38 || event.keyCode == 40) {
if (event.keyCode == 38 && ind > 0) {
change = caretInfo();
if (change) {
ind--;
}
} else if (event.keyCode == 40 && ind < document.querySelectorAll('.root p').length - 1) {
change = caretInfo(false);
if (change) {
ind++;
}
}
if (change) {
let cur = document.querySelectorAll('.root p')[ind];
cur.focus();
}
}
})
* {
box-sizing: border-box;
}
.root {
max-width: 600px;
margin: 1rem auto;
}
.root:focus,
.block:focus {
outline: 0;
}
.is-selected {
background-color: #f4f8ff !important;
border: 1px solid #deebff !important;
}
<div class="root">
<p name="jYdi0" class="block" tabindex="0" contenteditable>1</p>
<p name="Hdy89" class="block" tabindex="0" contenteditable>It was single line but now it's multiple line Just amazine what can be happen here. Here is the problem try to click "me" and then press arrow up. Ops :( but it should be on the first line</p>
<p name="wEldk" class="block" tabindex="0" contenteditable>lorem ipsumlorem ipsumlorem ipsum3</p>
</div>
You can also do something like
document.addEventListener("keypress", (event) => {
if(event.which === someEventCode) {
// your code here
}
})
Here, the someEventCode variable is different for different key presses.

How can I customize an interface and save it so it can be accessed again?

I am experimenting with Javascript drag and drop. I have built a simple interface editable with drag and drop features.
Here my index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css">
<title>Drag&Drop</title>
</head>
<body>
<div class="empty">
<div class="item" draggable="true"></div>
</div>
<div class="empty"></div>
<div class="empty"></div>
<div class="empty"></div>
<div class="empty"></div>
<script src="js/main.js"></script>
</body>
</html>
Here my style.css
body {
background: white;
}
.lists {
display: flex;
flex:1;
width 100%;
overflow-x:scroll;
}
.item {
background-image: url('http://source.unsplash.com/random/150x150');
position: relative;
height: 150px;
width: 150px;
top: 5px;
left: 5px;
cursor: pointer;
}
.empty {
display: inline-block;
height: 160px;
width: 160px;
margin: 5px;
border: 3px blue;
background-color: lightgray;
}
.hold {
border: solid lightgray 4px;
}
.hovered {
background: darkgray;
border-style: dashed;
}
.invisible {
display: none;
}
Here my main.js:
const item = document.querySelector('.item');
const empties = document.querySelectorAll('.empty');
//Item Listeners
item.addEventListener('dragstart',dragStart);
item.addEventListener('dragend',dragEnd);
//Loop through empties
for (const empty of empties) {
empty.addEventListener('dragover', dragOver);
empty.addEventListener('dragenter', dragEnter);
empty.addEventListener('dragleave', dragLeave);
empty.addEventListener('drop', dragDrop);
}
//Drag Functions
function dragStart() {
console.log('Start');
this.className += ' hold';
setTimeout(()=> this.className = 'invisible', 0);
}
function dragEnd() {
console.log('End');
this.className = 'item';
}
function dragOver(e) {
console.log('Over');
e.preventDefault();
}
function dragEnter(e) {
console.log('Enter');
e.preventDefault();
this.className += ' hovered';
}
function dragLeave() {
console.log('Leave');
this.className = 'empty';
}
function dragDrop() {
console.log('Drop');
this.className = 'empty';
this.append(item)
}
Ok. Let's imagine that I am a user who moved the picture from the first box to the fourth box. When I login the next time, I am expecting to see the picture on the fourth box.
The questions are:
how do I save the new user's layout?
how do I recall it when I open the page again?
I am not interested in the "backend" part. I just want to understand how to extract info from a custom layout built with Javascript and how to rebuild it on a new page.
Many thanks!
What you can do is save the index in the list of "empty" class elements in local storage. Check out the new JS code:
const empties = document.querySelectorAll('.empty');
let storage = JSON.parse(localStorage.getItem("elementLocation")).location
let storeData = {location: storage}
if (storage !== null) {
let array = document.getElementsByClassName("empty");
array[0].innerHTML = "";
array[storage].innerHTML = '<div class="item" draggable="true">'
alert(storage)
}
const item = document.querySelector('.item');
//Item Listeners
item.addEventListener('dragstart',dragStart);
item.addEventListener('dragend',dragEnd);
//Loop through empties
for (const empty of empties) {
empty.addEventListener('dragover', dragOver);
empty.addEventListener('dragenter', dragEnter);
empty.addEventListener('dragleave', dragLeave);
empty.addEventListener('drop', dragDrop);
}
//Drag Functions
function dragStart() {
this.className += ' hold';
setTimeout(()=> this.className = 'invisible', 0);
}
function dragEnd() {
this.className = 'item';
}
function dragOver(e) {
e.preventDefault();
}
function dragEnter(e) {
e.preventDefault();
this.className += ' hovered';
}
function dragLeave() {
this.className = 'empty';
}
function dragDrop() {
this.className = 'empty';
this.append(item);
let parentArray = document.getElementsByClassName("empty");
storeData.location = [].indexOf.call(parentArray, this);
localStorage.removeItem('elementLocation');
localStorage.setItem('elementLocation', JSON.stringify(storeData));
alert(JSON.parse(localStorage.getItem("elementLocation")).location);
}
Here's the JSFiddle: https://codepen.io/mero789/pen/eYpvYVY
This is the new main.js thanks to Ameer input
const empties = document.querySelectorAll('.empty');
let storage = JSON.parse(localStorage.getItem("elementLocation"))
let storeData = {location: storage}
if (storage == null) {
console.log("Storage Non Existing")
}
else {
console.log("Storage Existing")
console.log(storage.location)
let array = document.getElementsByClassName("empty");
array[0].innerHTML = "";
array[storage.location].innerHTML = '<div class="item" draggable="true">'
alert(storage.location)
}
const item = document.querySelector('.item');
//Item Listeners
item.addEventListener('dragstart',dragStart);
item.addEventListener('dragend',dragEnd);
//Loop through empties
for (const empty of empties) {
empty.addEventListener('dragover', dragOver);
empty.addEventListener('dragenter', dragEnter);
empty.addEventListener('dragleave', dragLeave);
empty.addEventListener('drop', dragDrop);
}
//Drag Functions
function dragStart() {
this.className += ' hold';
setTimeout(()=> this.className = 'invisible', 0);
}
function dragEnd() {
this.className = 'item';
}
function dragOver(e) {
e.preventDefault();
}
function dragEnter(e) {
e.preventDefault();
this.className += ' hovered';
}
function dragLeave() {
this.className = 'empty';
}
function dragDrop() {
this.className = 'empty';
this.append(item);
let parentArray = document.getElementsByClassName("empty");
storeData.location = [].indexOf.call(parentArray, this);
localStorage.removeItem('elementLocation');
localStorage.setItem('elementLocation', JSON.stringify(storeData));
alert(JSON.parse(localStorage.getItem("elementLocation")).location);
}

Calculate the word amount from an <input>?

The following code converts text into equal paragraphs, based on the users input character amount.
Is it possible for the input box to calculate the amount of words for each paragraph instead of being based on the character amount?
JSFiddle
If an updated fiddle could please be provided, would be much appreciated, as I am still new to coding.
Thank You!
$(function() {
$('select').on('change', function() {
//Lets target the parent element, instead of P. P will inherit it's font size (css)
var targets = $('#content'),
property = this.dataset.property;
targets.css(property, this.value);
sameheight('#content p');
}).prop('selectedIndex', 0);
});
var btn = document.getElementById('go'),
textarea = document.getElementById('textarea1'),
content = document.getElementById('content');
chunkSize = 100;
btn.addEventListener('click', initialDistribute);
content.addEventListener('keyup', handleKey);
content.addEventListener('paste', handlePaste);
function initialDistribute() {
custom = parseInt(document.getElementById("custom").value);
chunkSize = (custom>0)?custom:chunkSize;
var text = textarea.value;
while (content.hasChildNodes()) {
content.removeChild(content.lastChild);
}
rearrange(text);
}
function rearrange(text) {
var chunks = splitText(text, false);
chunks.forEach(function(str, idx) {
para = document.createElement('P');
para.classList.add("Paragraph_CSS");
para.setAttribute('contenteditable', true);
para.textContent = str;
content.appendChild(para);
});
sameheight('#content p');
}
function handleKey(e) {
var para = e.target,
position,
key, fragment, overflow, remainingText;
key = e.which || e.keyCode || 0;
if (para.tagName != 'P') {
return;
}
if (key != 13 && key != 8) {
redistributeAuto(para);
return;
}
position = window.getSelection().getRangeAt(0).startOffset;
if (key == 13) {
fragment = para.lastChild;
overflow = fragment.textContent;
fragment.parentNode.removeChild(fragment);
remainingText = overflow + removeSiblings(para, false);
rearrange(remainingText);
}
if (key == 8 && para.previousElementSibling && position == 0) {
fragment = para.previousElementSibling;
remainingText = removeSiblings(fragment, true);
rearrange(remainingText);
}
}
function handlePaste(e) {
if (e.target.tagName != 'P') {
return;
}
overflow = e.target.textContent + removeSiblings(fragment, true);
rearrange(remainingText);
}
function redistributeAuto(para) {
var text = para.textContent,
fullText;
if (text.length > chunkSize) {
fullText = removeSiblings(para, true);
}
rearrange(fullText);
}
function removeSiblings(elem, includeCurrent) {
var text = '',
next;
if (includeCurrent && !elem.previousElementSibling) {
parent = elem.parentNode;
text = parent.textContent;
while (parent.hasChildNodes()) {
parent.removeChild(parent.lastChild);
}
} else {
elem = includeCurrent ? elem.previousElementSibling : elem;
while (next = elem.nextSibling) {
text += next.textContent;
elem.parentNode.removeChild(next);
}
}
return text;
}
function splitText(text, useRegex) {
var chunks = [],
i, textSize, boundary = 0;
if (useRegex) {
var regex = new RegExp('.{1,' + chunkSize + '}\\b', 'g');
chunks = text.match(regex) || [];
} else {
for (i = 0, textSize = text.length; i < textSize; i = boundary) {
boundary = i + chunkSize;
if (boundary <= textSize && text.charAt(boundary) == ' ') {
chunks.push(text.substring(i, boundary));
} else {
while (boundary <= textSize && text.charAt(boundary) != ' ') {
boundary++;
}
chunks.push(text.substring(i, boundary));
}
}
}
return chunks;
}
#text_land {
border: 1px solid #ccc;
padding: 25px;
margin-bottom: 30px;
}
textarea {
width: 95%;
}
label {
display: block;
width: 50%;
clear: both;
margin: 0 0 .5em;
}
label select {
width: 50%;
float: right;
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
body {
font-family: monospace;
font-size: 1em;
}
h3 {
margin: 1.2em 0;
}
div {
margin: 1.2em;
}
textarea {
width: 100%;
}
button {
padding: .5em;
}
p {
/*Here the sliles for OTHER paragraphs*/
}
#content p {
font-size: inherit;
/*So it gets the font size set on the #content div*/
padding: 1.2em .5em;
margin: 1.4em 0;
border: 1px dashed #aaa;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>Import Text below, then press the button</h3>
<textarea id="textarea1" placeholder="Type text here, then press the button below." rows="5">
</textarea>
<input style="width:200px;" id="custom" placeholder="Custom Characters per box">
<br>
<button style="width:200px;" id="go">Divide Text into Paragraphs</button>
</div>
<div>
<h3 align="right">Divided Text Will Appear Below:</h3>
<hr>
<div id="content"></div>
</div>
How about this? It uses jQuery, but as you used the library in your original submission, I hope that won't be an issue:
HTML
<textarea id="input"></textarea>
<br/>
<button id='divide'>Divide</button>
<div id="paras"></div>
CSS
#input {
resize: none;
height: 200px;
width: 100%;
}
JS
$(function() {
$("#divide").click(function() {
var text = $("#input").val();
var wpp = 10 // words per paragraph
var words = text.split(" ");
var paras = [];
for (i = 0; i < words.length; i += wpp) {
paras.push(words.slice(i, i + wpp).join(" "));
}
$.each(paras, function(i, para) {
$("#paras").append("<p>" + para + "</p>");
});
});
})
JSFiddle

undefined, image, strange text where there should be an image

i am trying to write a program, the code for which is below, but when i drag an image onto the page, it takes many attempts to actually load it.
here is my code:
<html>
<head>
<style>
#main { position:absolute; top:10px; left:50%; margin-left:-450px; width:900px; height:900px; border:dashed 1px lightgrey; padding:1em; }
#trash { background-color:#e9e9e9; margin-top:10px; width:200px; height:200px; border:dotted 4px lightgrey; position:absolute; top:0px; left:5px; margin-left:2em; text-align:center; }
#new { background-color:#e9e9e9; width:200px; height:200px; border:dotted 5px lightgrey; margin-right:1em; margin-bottom:.7em; float:right; }
.new { float:right; margin-right:1.5em; }
.drag { float:left; resize:both; overflow:hidden; height:110px; width:110px; }
.square { background-color:none; width:10px; height:10px; float:left; }
.drag * { resize:none; width:100px; height:100px }
.block { background-color:red; }
</style>
<script src="jq/jquery-1.9.1.js"></script>
<script src="jq/jquery-ui.js"></script>
<script>
if(window.FileReader) {
var imgcontent,imgdropped;
var dropElement;
addEventHandler(window, 'load', function() {
dropElement = document.getElementById('new');
var list = document.getElementById('new');
function cancel(e) {
if (e.preventDefault) { e.preventDefault(); }
return false;
}
// Tells the browser that we *can* drop on this target
addEventHandler(dropElement, 'dragover', cancel);
addEventHandler(dropElement, 'dragenter', cancel);
addEventHandler(dropElement, 'drop', function (e) {
e = e || window.event; // get window.event if e argument missing (in IE)
if (e.preventDefault) { e.preventDefault(); } // stops the browser from redirecting off to the image.
var dt = e.dataTransfer;
var files = dt.files;
for (var i=0; i<files.length; i++) {
var file = files[i];
var reader = new FileReader();
//attach event handlers here...
reader.readAsDataURL(file);
addEventHandler(reader, 'loadend', function(e, file) {
var bin = this.result;
var img = document.createElement("img");
img.file = file;
img.src = bin;
imgcontent = img.outerHTML;
additem();
}.bindToEventHandler(file));
}
return false;
});
Function.prototype.bindToEventHandler = function bindToEventHandler() {
var handler = this;
var boundParameters = Array.prototype.slice.call(arguments);
//create closure
return function(e) {
e = e || window.event; // get window.event if e argument missing (in IE)
boundParameters.unshift(e);
handler.apply(this, boundParameters);
}
};
});
} else {
document.getElementById('status').innerHTML = 'Your browser does not support the HTML5 FileReader.';
}
function addEventHandler(obj, evt, handler) {
if(obj.addEventListener) {
// W3C method
obj.addEventListener(evt, handler, false);
} else if(obj.attachEvent) {
// IE method.
obj.attachEvent('on'+evt, handler);
} else {
// Old school method.
obj['on'+evt] = handler;
}
}
</script>
<script>
var blockcolors = ["red","blue","green","yellow","white","black","lightgrey","lightblue","Chartreuse","Cyan","DarkGoldenRod","SlateGray","Tan","Purple","Maroon","MistyRose"];
var bcolor = 1;
var id = 2;
function drag(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}
function drop(ev)
{
ev.preventDefault();
ev.target.appendChild(document.getElementById(ev.dataTransfer.getData("Text")));
}
function droptrash(ev)
{
ev.preventDefault();
$("#"+ev.dataTransfer.getData("Text")).remove();
}
function change(div)
{
var divw=parseInt(div.style.width);
var divh=parseInt(div.style.height);
var imgw=divw-10;
var imgh=divh-10;
div.children[0].style.width=imgw;
div.children[0].style.height=imgh;
div.style.border="dotted 3px grey";
}
function makeGrid()
{
var main = $("#main");
for (var i = 0; i < 8100; i++)
{
var square = document.createElement('div');
square.setAttribute('class', 'square');
square.ondragover = function(event) { event.preventDefault(); };
square.ondrop = function(event) { drop(event); };
main.prepend(square);
}
}
function additem()
{
var newbox = document.getElementById("new");
newbox.innerHTML = '<div id="div'+id+'" class="drag" onmouseout="this.style.border=0" draggable="true" ' +
'ondragstart="drag(event)" onmousemove="change(this)"></div>';
div = document.getElementById("div"+id);
div.innerHTML = $("#newtype").val();
id+=1;
}
function blockcolor(block)
{
block.style.backgroundColor = blockcolors[bcolor];
if (bcolor == blockcolors.length-1)
bcolor = -1;
bcolor++;
}
</script>
</head>
<body onload="makeGrid()" class="new">
<div id="new"></div>
<div style="clear:both"></div>
<select onchange="additem()" value="heading" id="newtype" class="new">
<option onclick="this.value=imgcontent;">Image</option>
<option value="<textarea></textarea>">Text box</option>
<option value="<div onclick='blockcolor(this)' class='block'></div>">Block</option>
<option onclick="this.value='<h1 style=margin:0px>' + prompt('please enter some text') + '</h1>';">heading</option>
<option onclick="this.value='<h3 style=margin:0px>' + prompt('please enter some text') + '</h3>';">sub heading</option>
</select>
<div style="clear:both"></div>
<center>
<div style="clear:both"></div>
<div ID="main" overflow="auto">
</div>
</center>
<div style="clear:both"></div>
<div id="trash" ondragover="event.preventDefault()" ondrop="droptrash(event)" overflow="auto"><big><br />Trash</big></div>
</body>
</html>
I am aware that lots of things arent working, but i am most concerened with the drag and drop image abilities. sorry for my bad explanation, I'm thirteen.

My jQuery callback is failing

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.

Categories