jQuery: Div elements are not showing up - javascript

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>

Related

JavaScript moving text animation doesn't work. FULL CODE

JS: My problem is in running the following JS script, it's supposed to be very easy ,i think, but i can't understand why won't it run. I've just started coding and i'm already stuck in this problem. I want the text to go up (by increasing the bottom in CSS) for 5px until it reaches pos=6 ; then clearInterval should do its job.
CSS: I've put the position of div's to RELATIVE as i've read in some tutorials but didn't put the " container's " position to ABSOLUTE, may it be the problem?
<html>
<head>
<style>
html {
height: 100%;
}
body {
height: ;
width: 100%;
background-color: ;
margin: 0px;
padding: 0px;
}
#generale {
height: 100%;
width: 100%;
}
#intestazione {
height: 7%;
width: 100%;
float: left;
background-image: url(immagini/sfumatura.png);
position: static;
}
#profilo {
position: static;
float: right;
width: 12%;
height: 100%;
}
.testo_rialzato {
position: relative;
float: right;
width: auto;
height: 100%;
padding-left: 20px;
padding-right: 20px;
background-color: transparent;
}
</style>
</head>
<body>
<div id="generale">
<div id="intestazione">
<div id="profilo"></div>
<div class="testo_rialzato sumba">
<p>Sp</p>
</div>
<div class="testo_rialzato ap">
<p>App</p>
</div>
<div class="testo_rialzato te">
<p>Te</p>
</div>
<div class="testo_rialzato do">
<p>Dom</p>
</div>
<div class="testo_rialzato big">
<p style="line-height:70%; margin-top:8px; text-align:center;">Big</p>
</div>
</div>
<script>
var ez = document.querySelectorAll(".sumba , .ap , .te , .do, .big");
ez.onmouseover = alza();
var intervallo = setInterval(alza, 100);
function alza() {
var pos = 0;
if (pos = 6) {
clearInterval(intervallo);
} else {
ez.style.bottom = pos + "px";
}
}
</script>
</div>
</body>
</html>
First thing is , why declaring you are using event on an array of dome node (result of querySelectorAll will return array of domenodes ) so in order to attach mouseover and also apply some style you have to loop around those nodes .
Seconde thing while declaring set interval, its usless to use mousemovehere ?
Also the condition if is wrong you're using assignment , so you have to use == or === in order to make comaparison .
See below snippet :
var ez = document.querySelectorAll(".sumba , .ap , .te , .do, .big");
var pos = 0;
var intervallo = setInterval(alza, 100);
ez.forEach(function(el){
el.addEventListener("mouseover", alza);
})
function alza() {
if (pos == 25) {
clearInterval(intervallo);
} else {
ez.forEach(function(el){
el.style.bottom = pos + "px";
});
pos++;
}
}
.sumba, .ap {
position:absolute;
}
.ap {
color:red;
left:40px
}
<!-- begin snippet: js hide: false console: true babel: false -->
<div class="sumba">Text</div>
<div class="ap">Text 2</div>
try this
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
}
</style>
<body>
<p>
<button onclick="myMove()">Click Me</button>
</p>
<div id ="container">
<div id ="animate">ggg</div>
</div>
<script>
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.left = pos + 'px';
}
}
}
</script>
</body>
</html>

Animations not playing on load or on click in Javascript

Working on a tip calculator with an animation on an h1 tag and a slideDown and slideUp on click on the h2 tags. Problem is, none of the animations are playing and the click event isn't working either.
Here is the HTML file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tip Calculator</title>
<link rel="shortcut icon" href="images/favicon.ico">
<link rel="stylesheet" href="midtermcss.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<script src="animationJS.js"></script>
</head>
<body>
<section id="faqs">
<h1>Tip facts</h1>
<h2>Things to know before you tip</h2>
<div>
<p>Tips Account for 44 Billion dollars of the Food Industry</p>
<p>7 States require servers to be paid minimum wage like everyone else</p>
<ul>
<li>Minnessota</li>
<li>Montana</li>
<li>Washington</li>
<li>Oregon</li>
<li>California</li>
<li>Nevada</li>
<li>Alaska</li>
</ul>
<p>Current Federal minimum tipped wage is $2.13 per hour can you live on that?</p>
<p>Charging with Credit/Debit cards tends to reduce the average tip</p>
</div>
</section>
<section id="js">
<h1 id="heading">Tip Calculator</h1>
<label for="billAmount">Total Amount Of Bill:</label>
<input type="text" id="billAmount"><br>
<label for="percentTip">Percent To Tip:</label>
<input type="text" id="percentTip"><br>
<label for="amountPeople">How Many People?:</label>
<input type="text" id="amountPeople"><br>
<label for="totalTip">Tip Total:</label>
<input type="text" id="totalTip"><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>
</section>
</body>
</html>
Here is the JS file.
$(document).ready(function() {
// runs when an h2 heading is clicked
$("#faqs h2").toggle(
function() {
$(this).toggleClass("minus");
$(this).next().slideDown(1000, "easeOutBounce");
},
function() {
$(this).toggleClass("minus");
$(this).next().slideUp(1000, "easeInBounce");
}
);
$("#faqs h1").animate({
fontSize: "400%",
opacity: 1,
left: "+=375"
}, 1000, "easeInExpo")
.animate({
fontSize: "175%",
left: "-=200"
}, 1000, "easeOutExpo");
$("#faqs h1").click(function() {
$(this).animate({
fontSize: "400%",
opacity: 1,
left: "+=375"
}, 2000, "easeInExpo")
.animate({
fontSize: "175%",
left: 0
}, 1000, "easeOutExpo");
});
});
var $ = function(id) {
return document.getElementById(id);
}
var calculateClick = function() {
var billAmount = parseFloat($("billAmount").value);
var percentTip = parseFloat($("percentTip").value);
var amountPeople = parseInt($("amountPeople").value);
if (isNaN(billAmount) || billAmount <= 0) {
alert("Your bill can't be 0 or less.");
} else if (isNaN(percentTip) || percentTip <= 0) {
alert("The percentage should be a whole number.");
} else if (isNaN(amountPeople) || amountPeople <= 0) {
alert("You are 1 person never count yourself as less.");
} else {
var total = billAmount * (percentTip / 100) / amountPeople;
$("totalTip").value = total.toFixed(2);
}
}
window.onload = function() {
$("calculate").onclick = calculateClick;
$("billAmount").focus();
}
Last but not least the CSS file since the open and minus classes are listed in there
* {
margin: 0;
padding: 0;
}
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 500px;
border: 3px solid blue;
}
section {
padding: 0 1em .5em;
}
section.js {
padding: 0 1em .5em;
}
h1 {
text-align: center;
margin: .5em 0;
}
label {
float: left;
width: 10em;
text-align: right;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
#faqs h1 {
position: relative;
left: -168px;
font-size: 125%;
color: blue;
}
h2 {
font-size: 120%;
padding: .25em 0 .25em 25px;
cursor: pointer;
background: url(images/plus.png) no-repeat left center;
}
h2.minus {
background: url(images/minus.png) no-repeat left center;
}
div.open {
display: block;
}
ul {
padding-left: 45px;
}
li {
padding-bottom: .25em;
}
p {
padding-bottom: .25em;
padding-left: 25px;
}
I can't figure out for the life of me why the animations work in a separate test file but when I use them now in my tip calculator they don't. I'm using Murach's Javascript and Jquery book but this section has been terribly hard to understand.
Your issue is that you include jQuery but later on in the global scope you redefine the $:
var $ = function(id) {
return document.getElementById(id);
}
Fiddle: http://jsfiddle.net/AtheistP3ace/u0von3g7/
All I did was change the variable name holding that function and replace it in the areas you were using it. Specifically:
var getById = function(id) {
return document.getElementById(id);
}
var calculateClick = function() {
var billAmount = parseFloat(getById("billAmount").value);
var percentTip = parseFloat(getById("percentTip").value);
var amountPeople = parseInt(getById("amountPeople").value);
if (isNaN(billAmount) || billAmount <= 0) {
alert("Your bill can't be 0 or less.");
} else if (isNaN(percentTip) || percentTip <= 0) {
alert("The percentage should be a whole number.");
} else if (isNaN(amountPeople) || amountPeople <= 0) {
alert("You are 1 person never count yourself as less.");
} else {
var total = billAmount * (percentTip / 100) / amountPeople;
getById("totalTip").value = total.toFixed(2);
}
}
window.onload = function() {
getById("calculate").onclick = calculateClick;
getById("billAmount").focus();
}
$ is just shorthand for jQuery. When you include jQuery it creates two functions for you that both do the same thing. jQuery and $. If you set $ equal to something else you have effectively overwritten jQuery library included in your page and it will no longer operate as you would expect. All jQuery functionality begins with using $ or jQuery function. Once that returns a jQuery object to you, you can begin chaining and calling functions off those objects but to get a jQuery object you need to use the jQuery or $ function.
You mentioned in a comment above your teacher had you do that to fix something. I imagine it was because jQuery was not initially included so he just created the $ selector function to get you moving but I would hope he explained why he did that and how it can affect things later.

Count back percentage using JQuery

I have the code below where I'd like to the numbers count back to 0% once hover the object out. Also I can't figure our how to make the value disappear again as it was on load. Could you please help me solve this.
Thanks in advance.
HTML
<div class="container">
<div class="fill" data-width="80%"></div>
</div>
<div class="container">
<div class="fill" data-width="50%"></div>
</div>
CSS
.container {
position: relative;
width: 300px;
height: 30px;
background-color: blue;
margin: 10px auto;
}
.fill {
height: 100%;
width: 0;
background-color: red;
line-height: 30px;
text-align: left;
z-index: 1;
text-align: right;
}
JQuery
$(function() {
$('.container').hover( function(){
var width=$(this).find(".fill").data('width');
$(this).find(".fill").animate({ width: width }, {
duration:800,
step: function(now, fx) {
$(this).html(Math.round(now) + '%');
}
});
},
function(){
$(this).find(".fill").animate({ "width": "0px" }, 800);
});
});
jsFiddle http://jsfiddle.net/zp8pe069/
jsBin demo
CSS: set overflow: hidden to .fill to prevent the text being visible after the animation ends.
HTML: remove % from the data attribute
JS and here you go. all you need:
$('.container').hover(function( e ){
var $fill = $(this).find(".fill");
var width = $fill.data('width');
$fill.stop().animate({width: e.type=="mouseenter" ? width+"%" : "0%" }, {
duration : 800,
step : function(now) {
$(this).html(Math.round(now) + '%') ;
}
});
});
Note also the use of the .stop() method, if you hover multiple time hysterically :) it'll prevent endless animations.

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>

Scrolling text which is too long with jquery

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

Categories