i have multiple dynamic div ids in a while loop, this div id is to be used in JavaScript to display a radial progress bar. my problem is that although i have unique ids i cant pass this unique ids to my JavaScript to show the different radial progress for each. i have tried using div class but that just repeats the last id of the loop in all progress bars. i don't want to use links or hovers to get the unique id as i want the JavaScript to fire on page load. How can i make each div in my while loop display the progress the progress bar correctly.
sample.php
<?php
..................................
while($obj = $getcDetails->fetch()){
//div that displays radial progress bar
echo '
<div class="page" style="color:#000000;">
<div id="progress-pie-chart'.$Id.'" data-percent="'.$cId.'">
<div class="ppc-progress">
<div class="ppc-progress-fill"></div>
</div>
<div class="ppc-percents">
<div class="pcc-percents-wrapper">
<span>%</span>
</div>
</div></div></div>';
?>
sample.js
<script>
$(function(){
var $ppc = $('.progress-pie-chart'),//add dynamic id here to display multiple progress bar unique to that div
percent = parseInt($ppc.data('percent')),
deg = 360*percent/100;
if (percent > 50) {
$ppc.addClass('gt-50');
}
$('.ppc-progress-fill').css('transform','rotate('+ deg +'deg)');
$('.ppc-percents span').html(percent+'%');
});
</script>
Any help or guide is greatly appreciated.
You can base this logic off of just a class. Given that the progress fill and percents are children of the progress-pie-chart, you can find the ones you need to change, with a contextual lookup.
$(function(){
$('.progress-pie-chart').each(function(){
var $ppc = $(this)
, percent = parseInt($ppc.data('percent'))
, deg = 360*percent/100;
if (percent > 50) {
$ppc.addClass('gt-50');
}
$ppc.find('.ppc-progress-fill').css('transform','rotate('+ deg +'deg)');
$ppc.find('.ppc-percents span').html(percent+'%');
});
});
Related
I've 252 li's, their IDs defined by numbers between 1 and 252. What I'm trying to achieve is replacing text within a random li every time I click a h1. Yet this doesn't work. What am I missing?
$('h1').click(function() {
var flashNumber = Math.floor((Math.random() * 251) + 1);
$('#'+flashNumber).html('test');
});
The code looks fine. If your HTML is also just a list of <div>s, then I can only see one potential problem - the name of your div#ids. Prior to HTML5 they had to start with a letter. What doctype are you using? Maybe it behaves differently in different browsers?
Try adding a letter to your id names:
$(document).ready(function(){
$('h1').click(function() {
var flashNumber = Math.ceil((Math.random() * 251));
$('#my-divs-' + flashNumber).html('test');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Click</h1>
<div id="my-divs-1"></div>
<div id="my-divs-2"></div>
<div id="my-divs-3"></div>
<div id="my-divs-4"></div>
<div id="my-divs-5"></div>
<div id="my-divs-6"></div>
...
<div id="my-divs-251"></div>
What I'm trying to do is run a jQuery function that converts a number score into a bar rating system using the score as a percentage to set the width of the bar. The divs and the scores inside of the divs are being generated dynamically from XML with XSL.
The problem is that the function is taking the score from the first DIV and applying it to all subsequent DIVs instead of taking the score from each DIV separately. For reference, .Product_Rating_Score_Overall is the score, .ratingBar is the grey background behind my score bar, .ratingOverall is the green bar that has its width adjusted to reflect the score percentage. Here is an image of my rating system(as you can see the rating of 2.0 from the first DIV is being transferred to the other DIVs. The ratings for the other DIVs should be as follows 7.0 6.0, 6.0, 6.0 - these are just dummy scores for now):
Here is my html code:
<div id="F26_ResultsDiv" style="display:none">
<div class="items"><div class="ColOne">
<div class="item">
<div class="otherStuff">
<span>Kindermat Basic Red/Blue</span>
<div class="overall"><span><span class="content">
<ul>
<li class="Product_Rating_Score_Overall">2.00</li>
</ul>
</span></span>
<div class="ratingBar">
<div class="ratingOverall">
</div></div></div></div></div>
Here is my jQuery code:
$('.overall').each( function() {
var score = parseFloat($('.Product_Rating_Score_Overall').text()).toFixed(1);
console.log(score);
var scorePerc = score * 10;
$('.ratingOverall').width(scorePerc + '%');
$('.Product_Rating_Score_Overall').text(score);
});
Any help is really appreciated. Thanks so much.
You need to localize your selector:
$('.overall').each( function() {
var score = parseFloat($(this).find('.Product_Rating_Score_Overall').text()).toFixed(1);
console.log(score);
var scorePerc = score * 10;
$(this).find('.ratingOverall').width(scorePerc + '%');
$(this).find('.Product_Rating_Score_Overall').text(score);
});
Update: added fiddle https://jsfiddle.net/mbho2bjj/5/
Using $(this) and find() function.
for each element with class overall you find under it the element with class Product_Rating_Score_Overall
$('.overall').each( function() {
var score = parseFloat($(this).find('.Product_Rating_Score_Overall').text()).toFixed(1);
console.log(score);
var scorePerc = score * 10;
$(this).find('.ratingOverall').width(scorePerc + '%');
$(this).find('.Product_Rating_Score_Overall').text(score);
});
The problem is with your second line and the other references being global and not localized properly. You should be changing it to grab the local value, not the first one each time that appears on the global scope, which is why you are getting the functionality you see now. Right now you think its not working but it is working exactly as it was written. By adjusting the code to act on the local variables inside each '.overall' we will get the proper results that you are looking for.
Try changing that code like this:
$('.overall').each( function() {
var score = parseFloat($(this).find('.Product_Rating_Score_Overall').text()).toFixed(1);
console.log(score);
var scorePerc = score * 10;
$(this).find('.ratingOverall').width(scorePerc + '%');
$(this).find('.Product_Rating_Score_Overall').text(score);
});
I'm trying to generate random div widths for each database result that's output.
The code works when it's outside the loop, but every div is the same 'random' width.
load page and all divs are 200px
refresh page and all divs are 150px
refresh page and all divs are 250px ...etc.
The trouble being, I need each individual div to be a random width, not all the same random width... for that reason I've added my javascript inside the loop in order to get a new 'random' width each time a database value is output.
And of course, it's not working!
<?php
$result = mysql_query("SELECT * from tbl_status ORDER BY tbl_status.date desc");
while($row = mysql_fetch_array($result))
{
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var x = Math.floor((Math.random()*150)+150);
$('.statusCont').width(x+'px');
});
</script>
echo'
<div class="statusCont">
<div class="statusUsr">Tom Adams - Newcastle</div>
<div class="statusTxt"><p>' . $row['status'] . '</p></div>
</div><!-- ends .statusCont -->
';}
?>
The reason that all the div's have the same random width is because the jquery class selector $('.statusCont') will return all elements with that class. So when your loop prints out the last selector it applies to all of the previous loaded elements.
Instead of including the javascript in the php while loop you can just write a script in the head that will affect the page after it's loaded
$(document).ready(function () {
$('.statusCont').each(function () {
var x = Math.floor((Math.random() * 150) + 150);
$(this).width(x);
});
);
I have a page that looks like so:
<div id="container">
<div class="item">...</div>
<div class="item">...</div>
<div class="item">...</div>
<div class="item">...</div>
</div>
I was wondering if there is a way that I could insert a div randomly between any of the "item" divs, so when the page is loaded, it would look like:
<div id="container">
<div class="item">...</div>
<div class="item">...</div>
<div class="rondomDiv">...</div>
<div class="item">...</div>
<div class="item">...</div>
</div>
All the divs with the "item" class are dynamically generated, and cannot be modified. Any ideas?
Thanks in advance!
Try something like below,
var $items = $('#container').find('.item');
var pos = Math.floor(Math.random() * $items.length)
$('.randomDiv').insertAfter($items.eq(pos));
I'd suggest, pending further information:
$('.item').eq(
/* I'm using the eq() method to select a specific element,
and creating the random number (in the range from 0-(number-of-elements))
within the method to avoid creating unnecessary variables. */
Math.floor(Math.random() * $('.item').length)
/* after() creates an element from the html string, and inserts it after
the element selected earlier with the eq() method */
).after('<div class="random"></div>');
JS Fiddle demo.
A slightly altered, though more verbose, alternative to the above:
$('<div />', {
'class': 'random',
'text': '...'
}).insertAfter($('.item').eq(Math.floor(Math.random() * $('.item').length)));
JS Fiddle demo.
References:
after().
eq().
insertAfter().
Math.floor().
Math.random().
Code:
HTML:
<div id="container">
</div>
JS:
$(document).ready(function(){
for(var i =1; i<10; i++) {
$("#container").append("<div class='item' id='"+i+"'>Item</div>"); /*adding item divs dynamically */
}
/*the real magic is below */
var rand_id = Math.floor((Math.random()*10)+1); /*generating an item divs ID randomly */
$("#"+rand_id).after("<div class='randomDiv'>Random DIv</div>"); /*adding the random div after that div of the rand_id */
});
Fiddle: http://jsfiddle.net/mareebsiddiqui/ULcTc/
Explanation:
This is simple. First I add the item divs dynamically by giving them ID's respectively with starting from 1 and ending on 10. Then I generate a random ID using Math.floor() and Math.random() JavaScript functions. Then I fetch(using a simple technique) the div with that random ID and then after that div I add a random div.
I will not provide code if you tried nothing.
But if you don't know where to start and need a workflow :
Coun't the number of div in container Create a random number between 0 and the number of div.
Append your div after the div with the random number index.
This will work:
function randomDiv() {
var divCount = $(".item").length;
var randomnumber=Math.floor(Math.random()*divCount);
$("div.item:eq(" + randomnumber + ")").after("<div class='randomDiv'>hey im random</div>");
}
Demo: http://jsfiddle.net/meaFv/
This is a case where the non-jQuery answer is equivalent to the jQuery answer, in terms of lines of code:
// Assuming you already have a reference to the random div at "randomDiv"
var container = document.getElementById('container');
var position = Math.floor(Math.random() * container.childNodes.length);
container.insertBefore(randomDiv, childNodes[position]);
Example here: http://jsfiddle.net/qbqfR/ Press RUN a bunch of times to see it in action.
var x=Math.floor(Math.random()*$('#container').children().length);
$('#container div').eq(x).append('<div class="rondomDiv">YAY</div>');
itemLength = $('#container .item').length; //quantity of .items
randomPlace = Math.floor((Math.random()*itemLength)); //some random from 0 to .item length
randomDiv = $('<div />',{
'class':'randomDiv',
text: randomPlace
}); //.randomDiv
$('#container .item').eq(randomPlace).after(randomDiv); //place it after the .item of position 'randomPlace'
http://jsfiddle.net/RaphaelDDL/4tpCy/
Try this -
var $items = $('#container .item');
$items.eq(Math.floor(Math.random() * $items.length ))
.after("<div class='rondomDiv'></div>");
I'm trying to get jQuery plugin SmoothDivScroll (http://www.smoothdivscroll.com/) to start at the center of its contained content so there are scrollbars to the left and right on load. I'm aware that there's a startAtElementId option, but this doesn't allow me to start at the center.
I've tried calculating the centerpoint and applying it to the appropriate elements, but the left scroll always stops before it's expected to and the right elements float underneath.
Tried using this Js with no luck:
$("div#scroller").smoothDivScroll();
var halfWayDoc = $(document).width() / 2;
var halfWayScrollArea = $("#scroller .scrollableArea").width() /2;
var halfWay = halfWayDoc - halfWayScrollArea;
var scrollArea = $("#scroller .scrollableArea").width();
var scrollAreaAdjust = scrollArea + halfWay;
$("#scroller .item:first-child").css("margin-left",halfWay);
$("#scroller .item:last-child").css("margin-right",halfWay);
$("#scroller .scrollableArea").width(scrollAreaAdjust);
HTML looks like this:
<div id="scroller">
<div class="scrollingHotSpotLeft"></div>
<div class="scrollingHotSpotRight"></div>
<div class="scrollWrapper">
<div class="scrollableArea">
<div class="item">
<img src="assets/images/detail/Erdem-A-W-11-B2-sml.jpg" alt="example"/>
</div>
...
<div class="item">
<img src="assets/images/detail/Erdem-A-W-11-B2-sml.jpg" alt="example"/>
</div>
</div>
</div>
</div>
Any help or pointers are appreciated.
Cheers,
Shaun
Here is the solution that I suggest :-)
// Element for Scroll
var scrollElement = $("div#scroller");
// Enable Smooth Div Scroll
scrollElement.smoothDivScroll();
// Find out Scrollable area's width
var halfWidth = $("div#scroller .scrollableArea").width()/2;
// Force scroller to move to half width :-)
scrollElement.data("scrollWrapper").scrollLeft(halfWidth);
I update the fiddle, so you can take a look at this update one:
http://jsfiddle.net/3A9Zy/
I hope this helps :-)
The basic sample in the site http://www.smoothdivscroll.com/index.html#quickdemo is having the functionality implemented. The animation starts from an image with ID "startAtMe"
$("div#makeMeScrollable").smoothDivScroll({ autoScroll: "onstart",
autoScrollDirection: "backandforth",
autoScrollStep: 1,
autoScrollInterval: 15,
startAtElementId: "startAtMe",
visibleHotSpots: "always" });
. Did you try by specifying an id to the element you want to start with and passing the startAtElementId: "startAtMe" to the smoothDivScroll function?