Scrolling text which is too long with jquery - javascript

I am trying to create a music player/centre online.
I have a player that plays the music and displays the current track:
As you can see from th title of the song it is too long for the div. What i would like to do is scroll the text and reset it an rescroll etc.
I have attempted this with the below code:
html:
<div id="top-bar">
<div id="player-container">
<div id="player">
<div id="level1">
<div class="current-track"><h1><span id="title">Party All Night (Sleep All Day) -</span> Sean Kingston</h1></div>
<div class="add-to-playlist"></div>
<div class="share"></div>
</div>
<div class="clearfix"></div>
<div id="level2">
<div class="current-time">0:00</div>
<div class="progress"><span id="slider"></span></div>
<div class="total-time">3:43</div>
</div>
</div>
</div>
</div>
Jquery:
$(function() {
var scroll_text;
$('div.current-track').hover(
function() {
var $elmt = $(this);
scroll_text = setInterval(function() {
scrollText($elmt);
}, 5);
}, function() {
clearInterval(scroll_text);
$(this).find('div.current-track h1').css({
left: 0
});
});
var scrollText = function($elmt) {
var left = $elmt.find('div.current-track h1').position().left - 1;
left = -left > $elmt.find('div.current-track h1').width() ? $elmt.find('div.current-track').width() : left;
$elmt.find('div.current-track h1').css({
left: left
});
};
});​​
Any pointer would be appriciated
Here is a jsfiddle for you guys: JSfiddle
UPDATE
Could anybody tell me:
How to make this happen automatically? Done
How to slow the scrolling? Done
Here is the updated jsfiddle for you guys: JSfiddle

I think you are misunderstanding how jquery .find() works:
$elmt.find('div.current-track h1')
should be:
$elmt.find('h1')
http://jsfiddle.net/Dn6jx/5/
edit: updated fiddle for comments
http://jsfiddle.net/Dn6jx/15/

Added check to see if text is long enough to require scrolling, removed the clear interval, and wrapped in plugin.
JSFiddle update
$.fn.scrolltxt = function() {
var options = $.extend({
speed : 28
}, arguments[0] || {});
return this.each(function() {
var el = $(this);
if( el.find('span').width() > el.parent().width() ) {
var scroll_text = setInterval(function() {
scrollText();
}, options.speed);
};
var scrollText = function() {
var width = el.width(),
left = el.position().left - 1;
left = -left > width ? width : left;
el.css({left: left});
};
}); };
$('.current-track h1').scrolltxt();

A better way to animate the text (when the text is fully read => re-animate) :
JSFiddle update
$.fn.scrolltxt = function() {
var options = $.extend({
speed : 28
}, arguments[0] || {});
return this.each(function() {
var el = $(this);
if( el.find('span').width() > el.parent().width() ) {
var scroll_text = setInterval(function() {
scrollText();
}, options.speed);
};
var scrollText = function() {
var width = el.find('span').width(),
left = el.position().left - 1;
left = -left > width ? el.width() : left;
el.css({left: left});
};
});
};
$(function() {
$('.current-track h1').scrolltxt();
});

I improved the answer of Holiday Mat a bit.
If you want to replace the text with other text dynamically (which is not too long), the scrolling will still keeps place. You have to reset the interval somehow.
Another problem you might run into is, too many intervals are set and the text scrolls faster and faster.
Here a snippet which shows how I handled this. (I used h5 instead of h1, which you probably use somewhere else.) :
$.fn.scrolltxt = function() {
var options = $.extend({
speed: 28
}, arguments[0] || {});
return this.each(function() {
var $h5 = $(this);
var containerWidth = $h5.parent().width();
var textWidth = $h5.find('span').width();
var refreshIntervalId;
if (textWidth > containerWidth) {
refreshIntervalId = setInterval(function() {
scrollText();
}, options.speed);
$h5.data('refreshIntervalId', refreshIntervalId);
} else {
refreshIntervalId = $h5.data('refreshIntervalId');
if (refreshIntervalId != undefined) {
window.clearInterval(refreshIntervalId);
$h5.removeData('refreshIntervalId');
}
}
var scrollText = function() {
var textWidth = $h5.find('span').width();
var left = $h5.position().left - 1;
left = -left > textWidth ? $h5.width() : left;
$h5.css({
left: left
});
};
});
};
$('h5.scroll').scrolltxt();
#player {
width: 500px;
background: #000;
border: 1px solid #1f1f1f;
border-radius: 10px;
margin: 10px;
padding: 10px 20px;
}
.current-track {
height: 100%;
background: #333;
color: #FFF;
margin-right: 5px;
width: 100%;
font-size: 150%;
border-radius: 5px;
line-height: 30px;
overflow: hidden;
position: relative;
}
.current-track h5 {
position: relative;
white-space: nowrap;
line-height: 1.5em;
font-size: 1.5em;
}
* {
margin: 0;
padding: 0;
}
body {
font-family: Arial, Helvetica, sans-serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="player">
<div id="level1">
<div class="current-track">
<h5 class="scroll"><span><strong>KAFKA (The artist formerly known as Prince)</strong></span></h5>
</div>
<br /><br /><br />
<div class="current-track">
<h5 class="scroll"><span>The Most Beautiful Girl In The World (original 1995 version)</span></h5>
</div>
</div>
</div>
Or see the CodePen: https://codepen.io/r-w-c/pen/dyKoKQX

Related

Mobile browsers add a gap at the end of final element via css gap property

I'm back on Stack Overflow after a long time because I'm truly stuck at an issue I cannot get around even after hours piling up in front of the screen.
I have made a simple widget using CSS + HTML + JavaScript which scrolls elements in an overflowing-x container.
It works in a simple way, there is JavaScript code that adds a 205 value to the property scrollLeft of the overflowing container. The number comes from the fixed width of the images + the gap value which is 5px. Here is the code:
HTML:
<div id="controlContainer">
<a class="adButton" onclick="Scroll(-1)">❮</a>
<div id="topics">
<div class="adItem" onclick="ChangeTopic(1)">
<p>History</p>
<img src="images/other_samples/hundredgates.jpg">
</div>
<div class="adItem" onclick="ChangeTopic(2)">
<p>Oceans</p>
<img src="images/other_samples/goldensea.jpg">
</div>
<div class="adItem" onclick="ChangeTopic(3)">
<p>Sports</p>
<img src="images/other_samples/kite_surf.jpg">
</div>
<div class="adItem" onclick="ChangeTopic(4)">
<p>Travel</p>
<img src="images/other_samples/antiparos_church.jpg">
</div>
<div class="adItem" onclick="ChangeTopic(5)">
<p>Nightlife</p>
<img src="images/other_samples/nightlife.png">
</div>
</div>
<a class="adButton" onclick="Scroll(1)">❯</a>
</div>
CSS:
#controlContainer {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
gap: 20px;
}
#topics {
display: inherit;
gap: 5px;
overflow:hidden;
white-space: nowrap;
scroll-behavior: smooth;
}
.adItem {
position: relative;
}
.adItem img {
width: 200px;
height: 200px;
object-fit: cover;
border-radius: 20px;
}
.adItem p {
position: absolute;
left: 16px;
top: 8px;
text-align: center;
color: #ffff;
font-family: Georgia, "Times New Roman", Times, serif;
font-size: 50px;
margin: 0px;
user-select: none;
pointer: default:
}
And finally JS, which still needs some work tbh:
var LastClick;
var Delay = 300;
var SelectedElement;
var adControl;
var currentScroll;
window.onload = function () {SelectedElement = document.getElementById("ad1"); adControl = document.getElementById("topics"); resizeController();};
window.onresize = debounce(() => resizeController());; //resize the container when the screen does
//window.addEventListener('DOMContentLoaded', (event) => {SelectedElement = document.getElementById("ad1")});
function Scroll(n) {
if (LastClick >= (Date.now() - Delay)) {
return;
}
if (n == 1) {
adControl.scrollLeft += 205;
checkPos();
} else if (n == -1) {
adControl.scrollLeft -= 205;
checkPos();
}
LastClick = Date.now();
console.log(adControl.scrollLeft);
}; // This function is what's handling scrolling. THey are called via onclick events on the HTML Button elements
function checkPos() {
var elementWidth = adControl.scrollLeft;
if (elementWidth % 5 === 0) {
// do nothing
} else {
var newWidth = Math.ceil(elementWidth/5)*5;
console.log("old width: %s, new width: %s", elementWidth, newWidth)
adControl.scrollLeft = newWidth;
}
}; //Some position checks... it basically calculates if scrollLeft is divisible by 5, because all images are 200px long plus the 5px gap, so that should always be a multiple of 5.
function ChangeTopic(id) {
SelectedElement.style.display = "none";
SelectedElement = document.getElementById("ad" + id);
SelectedElement.style.display = "flex";
}; //That just changes the topic of another element.
function debounce(func, timeout = 1000){
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => { func.apply(this, args); }, timeout);
};
}; //This is a debounce function for the resize event, it prevents it from firing it too much.
function resizeController() {
adControl.style.maxWidth = "";
var elementWidth = adControl.offsetWidth;
var scroll = adControl.ScrollLeft;
var itemNo = (Math.floor(elementWidth / 200))
if (itemNo > 3) {
itemNo = 3
};
var newWidth = (itemNo*200);
newWidth = newWidth+(5*itemNo)
adControl.style.maxWidth = (newWidth + "px");
if (currentNo = itemNo) {
adControl.scrollLeft = scroll;
}
}; //resizes the container if need be (for mobile or tablet devices)
It actually works very well on Desktop, but on mobile, the CSS gap property which adds the gap between the images also adds a gap at the last element, like this:
That's even when I use a different browser from Firefox, like Chrome
On desktop, this gap does not exist, regardless of browser once again:
What is this? And how can I solve it? The main problem this causes is it will scroll in that tiny 5 gap space, which throws the position of my elements out of place, making them look like this:
I've thought of different methods like checking the property of ScrollLeft to detect when the view is out of the elements, but that property is completely unpredictable. For instance, when I scroll to the beginning of the element, it's not going to be necessarily zero, and even if I reach the end, the 205 value will be added even if there is not any space on the container. So that isn't reliable.
In short, I'd either need some kind of method to keep that gapping behaviour in check or solve the root problem altogether.
Yes... I'm not using any framework at all, my entire project is built on pure JavaScript. I'm not sure why I did this to myself, but oh well, all the challenge I guess.
Try and resize your font on the paragraph elements in your
div class="adItem" it appears to be overlapping the container and causing what would appear to be extra padding and i don't think it's happening on the others because the text is not long enough on others.
var LastClick;
var Delay = 300;
var SelectedElement;
var adControl;
var currentScroll;
window.onload = function () {SelectedElement = document.getElementById("ad1"); adControl = document.getElementById("topics"); resizeController();};
window.onresize = debounce(() => resizeController());; //resize the container when the screen does
//window.addEventListener('DOMContentLoaded', (event) => {SelectedElement = document.getElementById("ad1")});
function Scroll(n) {
if (LastClick >= (Date.now() - Delay)) {
return;
}
if (n == 1) {
adControl.scrollLeft += 205;
checkPos();
} else if (n == -1) {
adControl.scrollLeft -= 205;
checkPos();
}
LastClick = Date.now();
console.log(adControl.scrollLeft);
}; // This function is what's handling scrolling. THey are called via onclick events on the HTML Button elements
function checkPos() {
var elementWidth = adControl.scrollLeft;
if (elementWidth % 5 === 0) {
// do nothing
} else {
var newWidth = Math.ceil(elementWidth/5)*5;
console.log("old width: %s, new width: %s", elementWidth, newWidth)
adControl.scrollLeft = newWidth;
}
}; //Some position checks... it basically calculates if scrollLeft is divisible by 5, because all images are 200px long plus the 5px gap, so that should always be a multiple of 5.
function ChangeTopic(id) {
SelectedElement.style.display = "none";
SelectedElement = document.getElementById("ad" + id);
SelectedElement.style.display = "flex";
}; //That just changes the topic of another element.
function debounce(func, timeout = 1000){
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => { func.apply(this, args); }, timeout);
};
}; //This is a debounce function for the resize event, it prevents it from firing it too much.
function resizeController() {
adControl.style.maxWidth = "";
var elementWidth = adControl.offsetWidth;
var scroll = adControl.ScrollLeft;
var itemNo = (Math.floor(elementWidth / 200))
if (itemNo > 3) {
itemNo = 3
};
var newWidth = (itemNo*200);
newWidth = newWidth+(5*itemNo)
adControl.style.maxWidth = (newWidth + "px");
if (currentNo = itemNo) {
adControl.scrollLeft = scroll;
}
}; //resizes the container if need be (for mobile or tablet devices)
#controlContainer {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
gap: 20px;
}
#topics {
display: inherit;
gap: 5px;
overflow:hidden;
white-space: nowrap;
scroll-behavior: smooth;
}
.adItem {
position: relative;
}
.adItem img {
width: 200px;
height: 200px;
object-fit: cover;
border-radius: 20px;
}
.adItem p {
position: absolute;
left: 16px;
top: 8px;
text-align: center;
color: #ffff;
font-family: Georgia, "Times New Roman", Times, serif;
font-size: 50px;
margin: 0px;
user-select: none;
pointer: default:
}
<div id="controlContainer">
<a class="adButton" onclick="Scroll(-1)">❮</a>
<div id="topics">
<div class="adItem" onclick="ChangeTopic(1)">
<p>History</p>
<img src="images/other_samples/hundredgates.jpg">
</div>
<div class="adItem" onclick="ChangeTopic(2)">
<p>Oceans</p>
<img src="images/other_samples/goldensea.jpg">
</div>
<div class="adItem" onclick="ChangeTopic(3)">
<p>Sports</p>
<img src="images/other_samples/kite_surf.jpg">
</div>
<div class="adItem" onclick="ChangeTopic(4)">
<p>Travel</p>
<img src="images/other_samples/antiparos_church.jpg">
</div>
<div class="adItem" onclick="ChangeTopic(5)">
<p>Nightlife</p>
<img src="images/other_samples/nightlife.png">
</div>
</div>
<a class="adButton" onclick="Scroll(1)">❯</a>
</div>

How to change the text color of a transparent header on scroll, depending on the div it overlaps

I have a header with a transparent backgrounsd, and I am trying to get the text of the header to change colour between white and black depending on the background of the div it's overlapping.
So far I have managed to add a class of .color-menu to all the divs where I want the header to be black.
I then have it add a class of .dark-menu to the header when the .color-menu div reaches the top of the page.
The problem is that it only works for the first .colour-menu div. It will change to black when it is in the viewport and back to white for the next div but then when the next .color-menu div gets to the top it doesn't change.
So, it seems like the .each function isn't working but I am not sure how to fix it.
$(window).scroll(function() {
$('.color-menu').each(function(i){
var top_of_element = $(".color-menu").offset().top;
var bottom_of_element = $(".color-menu").offset().top + $(".color-menu").outerHeight();
var top_of_screen = $(window).scrollTop();
if ((top_of_screen > top_of_element) && (top_of_screen < bottom_of_element)) {
$(".header").addClass("dark-menu");
} else {
$(".header").removeClass("dark-menu");
}
});
});
UPDATE: I have also tried using $(this) but it really throws off when it changes color.
$(window).scroll(function() {
$('.color-menu').each(function(i){
var top_of_element = $(this).offset().top;
var bottom_of_element = $(this).offset().top + $(this).outerHeight();
var top_of_screen = $(window).scrollTop();
if ((top_of_screen > top_of_element) && (top_of_screen < bottom_of_element)) {
$(".header").addClass("dark-menu");
} else {
$(".header").removeClass("dark-menu");
}
});
});
Here is a simplified version of my code as an example:
$(document).ready(function() {
$(".white").addClass("color-menu");
$(".white-bold").addClass("color-menu");
$(".light").addClass("color-menu");
$(".light-bold").addClass("color-menu");
$(".bright").addClass("color-menu");
});
$(window).scroll(function() {
$('.color-menu').each(function(i){
var top_of_element = $(".color-menu").offset().top;
var bottom_of_element = $(".color-menu").offset().top + $(".color-menu").outerHeight();
var top_of_screen = $(window).scrollTop();
if ((top_of_screen > top_of_element) && (top_of_screen < bottom_of_element)) {
$(".header").addClass("dark-menu");
} else {
$(".header").removeClass("dark-menu");
}
});
});
.header {
width: 100%;
background: rgba(0,0,0,0);
margin: 0;
padding:10px;
position: fixed;
text-align: center;
}
.header a {
color: white;
font-size: 2rem;
text-transform: uppercase;
}
.dark-menu a{
color: black;
}
.black {
background-color: black;
height: 200px;
}
.white, .white-bold, .light, .light-bold, .bright {
background-color: white;
height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="header">
<a>This is the header</a>
</div>
<div class ="black"></div>
<div class ="white"></div>
<div class ="black"></div>
<div class ="white-bold"></div>
<div class ="black"></div>
<div class ="light"></div>
<div class ="black"></div>
<div class ="light-bold"></div>
<div class ="black"></div>
<div class ="bright"></div>
What is happening in your code is that on scroll, you loop through every color-menu div and add the class if it is the current one... but then the code continues to loop though the remaining elements in the array and removes it again because the page is not in the other div.
I've explained step-by-step the changes you need to get this to work after the example, but first you can see it working here:
Working Example:
$(document).ready(function() {
$(".white").addClass("color-menu");
$(".white-bold").addClass("color-menu");
$(".light").addClass("color-menu");
$(".light-bold").addClass("color-menu");
$(".bright").addClass("color-menu");
$(window).scroll(function() {
var inColorMenu = false; /* initialise var to store if we are in color-menu */
var top_of_screen = $(window).scrollTop(); /* just get this once outside loop */
/* Loop through each color-menu element and check if we are in one */
$('.color-menu').each(function(i) {
var top_of_element = $(this).offset().top;
var bottom_of_element = top_of_element + $(this).outerHeight();
/* if we are in a color-menu element, set our var to true and stop processing */
if ((top_of_screen > top_of_element) && (top_of_screen < bottom_of_element)) {
inColorMenu = true;
return false; /* N.B. need to return "false" to break from the "each" loop */
}
});
if (inColorMenu) {
$(".header").addClass("dark-menu");
} else {
$(".header").removeClass("dark-menu");
}
});
});
.header {
width: 100%;
background: rgba(0, 0, 0, 0);
margin: 0;
padding: 10px;
position: fixed;
text-align: center;
}
.header a {
color: white;
font-size: 2rem;
text-transform: uppercase;
}
.header.dark-menu a {
color: black;
}
.black {
background-color: black;
height: 200px;
}
.white,
.white-bold,
.light,
.light-bold,
.bright {
background-color: white;
height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="header">
<a>This is the header</a>
</div>
<div class="black"></div>
<div class="white"></div>
<div class="black"></div>
<div class="white-bold"></div>
<div class="black"></div>
<div class="light"></div>
<div class="black"></div>
<div class="light-bold"></div>
<div class="black"></div>
<div class="bright"></div>
How this works:
Declare a variable to record whether we are in a "color-menu" class or not, and initialise this to false, e.g.:
var inColorMenu = false;
When looping through $('.color-menu').each, if we are between the top and bottom of one of divs (which your code is already detecting), then set our variable to true to record this.
We can also return false to break the each loop and stop processing the rest of the elements (it will still work without this, we are just reducing the amount of processing required):
if ((top_of_screen > top_of_element) && (top_of_screen < bottom_of_element)) {
inColorMenu = true;
return false; /* N.B. need to return "false" to break from the "each" loop */
}
Finally, after we finish our $('.color-menu').each loop, if inColorMenu is true, we know we are in a color-menu div so we add the dark-menu class to the header, otherwise we remove it:
if (inColorMenu) {
$(".header").addClass("dark-menu");
} else {
$(".header").removeClass("dark-menu");
}
Note: You need to use $(this) when getting the offset().top and outerHeight() so that you are getting the values for the current element in the loop. $(".color-menu") gets the values for an unspecified element with this class so will not work.

Making a javascript popup draggable

I am creating a JavaScript popup. The code is as below.
The HTML:
<div id="ac-wrapper" style='display:none' onClick="hideNow(event)">
<div id="popup">
<center>
<h2>Popup Content Here</h2>
<input type="submit" name="submit" value="Submit" onClick="PopUp('hide')" />
</center>
</div>
</div>
The CSS:
#ac-wrapper {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: url("images/pop-bg.png") repeat top left transparent;
z-index: 1001;
}
#popup {
background: none repeat scroll 0 0 #FFFFFF;
border-radius: 18px;
-moz-border-radius: 18px;
-webkit-border-radius: 18px;
height: 361px;
margin: 5% auto;
position: relative;
width: 597px;
}
The Script:
function PopUp(hideOrshow) {
if (hideOrshow == 'hide') document.getElementById('ac-wrapper').style.display = "none";
else document.getElementById('ac-wrapper').removeAttribute('style');
}
window.onload = function () {
setTimeout(function () {
PopUp('show');
}, 0);
}
function hideNow(e) {
if (e.target.id == 'ac-wrapper') document.getElementById('ac-wrapper').style.display = 'none';
}
The jsFiddle Link:
http://jsfiddle.net/K9qL4/2/
The Issue:
The above script works fine, but I need to make the popUp draggable.
Here's some code that will do what you want. It relies only on an object called drag to store all its values, but you can easily alter that. The example relies on there being a div with the id of mydiv (a document.write() is used in this instance to supply that) that has a position attribute of absolute or fixed. You can see it in action at Jamie
document.write("<" + "div id='mydiv' style='background:blue; width:100px;"
"height:100px; position:fixed;'>" + "<" + "/div>");
var drag = new Object();
drag.obj = document.getElementById('mydiv');
drag.obj.addEventListener('mousedown', function(e)
{
drag.top = parseInt(drag.obj.offsetTop);
drag.left = parseInt(drag.obj.offsetLeft);
drag.oldx = drag.x;
drag.oldy = drag.y;
drag.drag = true;
});
window.addEventListener('mouseup', function()
{
drag.drag = false;
});
window.addEventListener('mousemove', function(e)
{
drag.x = e.clientX;
drag.y = e.clientY;
var diffw = drag.x - drag.oldx;
var diffh = drag.y - drag.oldy;
if (drag.drag)
{
drag.obj.style.left = drag.left + diffw + 'px';
drag.obj.style.top = drag.top + diffh + 'px';
e.preventDefault();
}
});
Use the
.draggable();
jquery function, here is your updated fiddle:
http://jsfiddle.net/N9rQK/
If you don't want to use jQuery, you should read this subject: Draggable div without jQuery UI

Drag and drop a div added into another div

Scenario
I am having a functionality in my project in which we have to add a note in a section and then it can be moved to the other sections. It is a sort of task tracking.
I am able to add a note dynamically created into one section and have made that note dragable. The note, sections are divs.
Problem
I am not able to drag the note to the other section or div. the note is draggable in its own section (div). Please help me with the solution so that it can be moved to other section.
Here is my HTML code:
<div id="addTaskDiv" style="height: 150px">
<a id="addTask" onclick="AddNote();">ADD Task</a> <a id="a1" onclick="AddText();">Submit</a>
</div>
<div id="MySplitter">
<div id="leftDiv" style="height: 150px; border-style: groove; width: 100%;">
left here
</div>
<div id="splitterUpperDiv">
<div id="midDiv" style="height: 150px; border-style: groove; width: 100%;">
middle here
</div>
<div id="rightDiv" style="height: 150px; width: 100%; border-style: groove;">
right here
</div>
</div>
</div>
Here is my .js
$().ready(function () {
$("#MySplitter").splitter();
$("#splitterUpperDiv").splitter();
$("#rightDiv").droppable();
$("#midDiv").droppable();
$("#leftDiv").droppable();
});
function AddNote(args, seder) {
var i = (typeof this.rel != 'undefined') && (this.rel - 0) == this.rel ? this.rel : 0;
var br = document.createElement("br");
$("#addTaskDiv")[0].appendChild(br);
addArea();
return false;
}
function addArea() {
var i = (typeof this.rel != 'undefined') && (this.rel - 0) == this.rel ? this.rel : 0;
var button = $(this);
var commentField = $('<textarea/>'); // create a textarea element
commentField[0].id = 'added' + i;
commentField
.css({
position: 'absolute',
width: 200, // textbox 200px by 100px
height: 100
})
// set the textarea's value to be the saved content, or a default if there is no saved content
.val(button.data('textContent') || 'This is my comment field\'s text')
// set up a keypress handler on the textarea
.keypress(function (e) {
if (e.which === 13) { // if it's the enter button
e.preventDefault(); // ignore the line break
button.data('textContent', this.value); // save the content to the button
$(this).remove(); // remove the textarea
}
})
.appendTo($("#addTaskDiv")[0]); // add the textarea to the document
}
function AddText() {
var i = (typeof this.rel != 'undefined') && (this.rel - 0) == this.rel ? this.rel : 0;
var a = $("#added0")[0].value;
var x = document.createElement("div");
x.width = '200px';
x.height = 'auto';
x.id = 'lable' + i;
this.rel = i + 1;
x.innerText = a;
var br = document.createElement("br");
$("#leftDiv")[0].appendChild(br);
$("#leftDiv")[0].appendChild(x);
$("#lable" + i + "").draggable();
}
You can try this :-
$("#rightDiv").droppable({
accept: '.draggableObject',
});
Please study this example code,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style type="text/css">
section{
background: rgba(0, 0, 0, .1);
padding: 20px;
height: 350px;
margin: 20px 0 0 0;
border-radius: 20px;
}
#myDiv{
cursor: move;
background: red;
height: 150px;
width: 150px;
float: left;
}
#targetDiv{
background: red;
height: 300px;
width: 300px;
float: right;
}
</style>
</head>
<body>
<script>
window.onload = function(){
var count=0;
var myDiv=document.getElementById('myDiv');
var targetDiv=document.getElementById('targetDiv');
myDiv.addEventListener('dragstart', function(e)
{
/* change ui to see clearly */
this.style.opacity= 0.2;
this.style.borderStyle= 'dashed';
targetDiv.style.backgroundColor= 'yellow';
/* set text from this as an argument to transfer */
e.dataTransfer.setData("Text", this.innerHTML);
}, false);
myDiv.addEventListener('dragend', function(e)
{
/* change ui to see clearly */
this.style.opacity=1;
this.style.borderStyle= 'solid';>
targetDiv.style.backgroundColor='red';
/* change text of dragend div */
this.innerHTML="Total Count : "+ (++count) ;
}, false);
targetDiv.addEventListener('dragover', function(e)
{
/* change ui to see clearly */
this.style.backgroundColor='green';
if(e.preventDefault){ e.preventDefault(); };
},false);
targetDiv.addEventListener('dragleave', function(e)
{
/* change ui to see clearly */
this.style.backgroundColor='yellow';
}, false);
targetDiv.addEventListener('drop', function(e)
{
/* get text from dropped div */
this.innerHTML= e.dataTransfer.getData("Text");
if( e.preventDefault ){ e.preventDefault(); };
},false);
}
</script>
<div draggable="true" id="myDiv">
Drag able Area.
</div>
<div id="targetDiv">
Target Area.
</div>
</body>
</html>

jQuery: Div elements are not showing up

I am adapting the Coverflow technique to work with a div. Following is the html:
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body,html {
margin: 0;
padding: 0;
background: #000;
height: 100%;
color: #eee;
font-family: Arial;
font-size: 10px;
}
div.magnifyme {
height: 80px;
padding: 80px;
position: absolute;
top: 0px;
left: 0px;
width: 2000px;
}
div.wrapper {
margin: 0px;
height: 470px;
/*border: 2px solid #999;*/
overflow: hidden;
padding-left: 40px;
right: 1px;
width: 824px;
position: relative;
}
div.container {position: relative; width: 854px; height: 480px; background: #000; margin: auto;}
div.nav {position: absolute; top: 10px; width: 20%; height: 10%; right: 1px; }
div.magnifyme div {
position: absolute;
width: 300px;
height: 280px;
float: left;
margin: 5px;
position: relative;
border: 2px solid #999;
background: #500;
}
</style>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript" src="ui.coverflow.js"></script>
<script type="text/javascript" src="ui.core.js"></script>
<script type="text/javascript">
$(function() {
$("div.magnifyme").coverflow();
$("#add").click(function() {
$(".magnifyme").append("<div id=\"div5\">hello world</div>");
$("div.magnifyme").coverflow();
});
});
</script>
</head>
<body>
<div class="container">
<div class="wrapper">
<div class="magnifyme">
<div id="div0">This is div 0</div>
<div id="div1">This is div 1</div>
<div id="div2">This is div 2</div>
<div id="div3">This is div 3</div>
<div id="div4">This is div 4</div>
</div>
</div>
<div class="nav">
<button type="button" id="add">Add to Deck</button>
</div>
</div>
</body>
</html>
The coverflow function (included as a js file in the head section) is here. When I click the button, I was expecting it to add a DIV to the already present deck. For some reason, it doesn't show the newly added DIV. I tried calling the coverflow() function after I added the new element but that didn't work either. The modified coverflow function is given here:
;(function($){
$.widget("ui.coverflow", {
init: function() {
var self = this;
this.items = $(this.options.items, this.element).bind("click", function() {
self.moveTo(this);
//$("div.slider").slider("moveTo", self.current, null, true);
});
this.itemWidth = this.items.outerWidth(true);
this.current = 0; //Start item
this.refresh(1, 0, this.current);
this.element.css("left",
(-this.current * this.itemWidth/2)
+ (this.element.parent()[0].offsetWidth/2 - this.itemWidth/2) //Center the items container
- (parseInt(this.element.css("paddingLeft")) || 0) //Subtract the padding of the items container
);
},
moveTo: function(item) {
this.previous = this.current;
this.current = !isNaN(parseInt(item)) ? parseInt(item) : this.items.index(item);
if(this.previous == this.current) return false; //Don't animate when clicking on the same item
var self = this, to = Math.abs(self.previous-self.current) <=1 ? self.previous : self.current+(self.previous < self.current ? -1 : 1);
$.fx.step.coverflow = function(fx) {
self.refresh(fx.now, to, self.current);
};
this.element.stop().animate({
coverflow: 1,
left: (
(-this.current * this.itemWidth/2)
+ (this.element.parent()[0].offsetWidth/2 - this.itemWidth/2) //Center the items container
- (parseInt(this.element.css("paddingLeft")) || 0) //Subtract the padding of the items container
)
}, {
duration: 1000,
easing: "easeOutQuint"
});
/*current = this.current;
$("[id^=div]").each(function() {
if(this.id != "div"+current) {
console.info(this.id + " Current: " + current);
$(this).fadeTo( 'slow', 0.1);
}
});*/
},
refresh: function(state,from,to) {
var self = this, offset = null;
this.items.each(function(i) {
var side = (i == to && from-to < 0 ) || i-to > 0 ? "left" : "right";
var mod = i == to ? (1-state) : ( i == from ? state : 1 );
var before = (i > from && i != to);
$(this).css({
webkitTransform: "matrix(1,"+(mod * (side == "right" ? -0.5 : 0.5))+",0,1,0,0) scale("+(1+((1-mod)*0.5))+")",
left: (
(-i * (self.itemWidth/2))
+ (side == "right"? -self.itemWidth/2 : self.itemWidth/2) * mod //For the space in the middle
),
zIndex: self.items.length + (side == "left" ? to-i : i-to)
});
if(!$.browser.msie)
$(this).css("opacity", 1 - Math.abs((side == "left" ? to-i : i-to))/2);
});
}
});
$.extend($.ui.coverflow, {
defaults: {
items: "> *"
}
});
})(jQuery);
One thing I did notice is that after clicking the button for about 5-10 times, the elements show up but not along with the already present divs but rather below them. I am guessing that this has something to do with the CSS of the magnifyme class (2000px), but I am not sure what it is. Is there any way I can make this work?
You need to write an additional function for the coverflow widget:
add: function(el) {
var self = this;
this.element.append(el)
this.options.items = $('> *', this.element);
this.items = $(this.options.items, this.element).bind("click", function() {
self.moveTo(this);
});
this.itemWidth = this.items.outerWidth(true);
this.moveTo(this.items.length-1);
},
and then call it like so:
$("#add").click(function() {
$("div.magnifyme").coverflow('add', "<div></div>");
});
First, you need to add a references to the jQuery UI core, and it also appears that it requires the jQuery slider plugin.
Second, in your click event you're doing a location.reload, which is refreshing the page from the server, resetting any changes you had made to the page. (if you make the DIVs much smaller you can see one flash in before the page is reloaded).
You are getting a js error on the page -- "$.widget is not a function" because you didn't include the jqueryUI library. http://jqueryui.com/
Also if you remove the location.reload line, your code will work, however, I would rewrite that script block like this, so that everything clearly runs when the document is ready:
<script type="text/javascript">
$(document).ready(function() {
$("div.magnifyme").coverflow();
$("#add").click(function() {
$(".magnifyme").append("<div id=\"div5\">hello world</div>");
$("div.magnifyme").coverflow();
});
});
</script>

Categories