I have just started out with .php/Java can someone show me how to get my bootstrap progress bar to increment in accordance with a users set time.
Progress Bar:
Code:
<div class="progress progress-striped active">
<div id="progressbar" class="bar" style="width: 0%;"></div>
User Input Example:
Code:
Set Seconds:
<input type="text" id="speed" value="10" />
<input type="submit" value="Start" onclick="doProgress();" />
Java Script {needed}:
Code:
<script type="text/javascript">
function doProgress()
{
Idk :( Please help.
};
</script>
(style="width: 0%;") Is the progress bars value 100% being maximum.
I want the value to increase in accordance to the users set value in seconds using this element I provided:
<input type="text" id="speed" value="10" />
example: the user enters 30 I want it to take 30 seconds for the progress bar to reach 100%
Something like this (untested):
function doIncrement(increment) {
w = parseInt(document.getElementById('progressBar').style.width);
document.getElementById('progressBar').style.width= (w + increment) +'%';
}
var w
var speed = document.getElementById('speed').value;
var increment = (speed/100);
for(var x = 0; x<speed; x++)
{
setTimeout(doIncrement(increment),1000);
}
The setTimeout approach (as per other answers) is the most common approach for animating time-based progress.
But I've had a problem with setTimeout if the speed is fast or when I want to reset the bar from 100% to 0%, as the default Bootstrap css transitions lead to undesirable animation effects (i.e takes 0.6 seconds to return to 0%). So I suggest tweaking the transition styling to match the desired animation effect e.g
pb = $('[role="progressbar"]')
// immediate reset to 0 without animation
pb.css('transition', 'none');
pb.css('width', '0%');
// now animate to 100% with setTimeout and smoothing transitions
pb.css('transition', 'width 0.3s ease 0s');
var counter = 0;
var update_progress = function() {
setTimeout(function() {
pb.attr('aria-valuenow', counter);
pb.css('width', counter + '%');
pb.text(counter + '%');
if(counter<100) {
counter++;
update_progress();
}
}, 5 * 1000 / 100); // 5 seconds for 100 steps
};
update_progress();
But if you're in the jQuery camp, then jQuery.animate is I think a neater approach as you can forget having to mess with css transition styling and counting steps etc e.g.
pb = $('[role="progressbar"]')
pb.css('transition', 'none'); // if not already done in your css
pb.animate({
width: "100%"
}, {
duration: 5 * 1000, // 5 seconds
easing: 'linear',
step: function( now, fx ) {
var current_percent = Math.round(now);
pb.attr('aria-valuenow', current_percent);
pb.text(current_percent+ '%');
},
complete: function() {
// do something when the animation is complete if you want
}
});
I've put a demo and more discussion on GitHub here.
I'm just learning bootstrap myself and came up with this for advancing it. As mentioned in other answers, the width CSS property appears to be what triggers the animation, but I initially didn't notice it and set the related aria attribute. You probably want to ensure setting the width results in other related attributes getting properly updated if a11y is important to you, setting them as necessary if not.
$( function() {
var bar = $('div.progress-bar');
var val = null;
i1 = setInterval(function() {
val = parseInt(bar.attr('aria-valuenow'));
val += 10;
console.log(val);
if( val < 101) {
bar.attr('aria-valuenow', val);
bar.css('width', val + '%');
} else {
clearInterval(i1);
}
}, 1000);
});
Try this:
//Find the div you want to update
var divArray = document.getElementById('progressbar');
//Set the width style
divArray.style.width = '100%';
Related
I added this shout box from http://www.saaraan.com/2013/04/creating-shout-box-facebook-style
a live demo of it can be seen here http://www.saaraan.com/2013/04/creating-shout-box-facebook-style
I have everything working properly except the slider itself. Every time I try to scroll up, it automatically scrolls back down. It wont stay in the up position. I think the problem is here.
// load messages every 1000 milliseconds from server.
load_data = {'fetch':1};
window.setInterval(function(){
$.post('shout.php', load_data, function(data) {
$('.message_box').html(data);
var scrolltoh = $('.message_box')[0].scrollHeight;
$('.message_box').scrollTop(scrolltoh);
});
}, 1000);
//method to trigger when user hits enter key
$("#shout_message").keypress(function(evt) {
if(evt.which == 13) {
var iusername = $('#shout_username').val();
var imessage = $('#shout_message').val();
post_data = {'username':iusername, 'message':imessage};
//send data to "shout.php" using jQuery $.post()
$.post('shout.php', post_data, function(data) {
//append data into messagebox with jQuery fade effect!
$(data).hide().appendTo('.message_box').fadeIn();
//keep scrolled to bottom of chat!
var scrolltoh = $('.message_box')[0].scrollHeight;
$('.message_box').scrollTop(scrolltoh);
//reset value of message box
$('#shout_message').val('');
More specifically here
var scrolltoh = $('.message_box')[0].scrollHeight;
$('.message_box').scrollTop(scrolltoh);
and here
//keep scrolled to bottom of chat!
var scrolltoh = $('.message_box')[0].scrollHeight;
$('.message_box').scrollTop(scrolltoh);
I have changed the 0 to 1 and other numbers and it fixes the scroll to work right but it doesn't show the latest shout, it will show shout 25 which is the last shout to be seen before deletion. Im not sure if this makes any sense but any help would be great.
The first link from top shows the whole code, the second link shows the example
Try this code, I didn't tested it. I hope it will work.
window.setInterval(function() {
$.post( 'shout.php', load_data, function( data ) {
var old_data = $(".message_box").html();
if ( old_data != data ) {
$(".message_box").html( data );
// get scrollHeight
var scrollHeight = $(".message_box").get(0).scrollHeight,
// get current scroll position
scrollTop = $(".message_box").scrollTop(),
// calculate current scroll percentage
percentage = Math.round( ( 100 / scrollHeight ) * scrollTop );;
// make sure user is not scrolled to top
if ( percentage > 80 ) {
$(".message_box").scrollTop( scrollTop );
}
}
});
}, 1000);
I am looking for a solution to display many items (10's of thousands) in a list view in Yii. I would like to be able to display them in a continually scrollable list. Here is the catch, when the user scrolls past the end of the list I want the new data to replace the data he just scrolled passed. Kind of like google music if you have a really long play list.
I looked at Yiinfinite-scroller but it appends to the end of the list making a very long list which is killing my memory usage.
Thanks
Its actuality really easy to implement infinite scroll in just a few lines of js and with the help of jQuery. Measure the height of the content div and as the page scrolls subtract the scroll difference from the divs height then when it hit the min amount do the query for more content and reset the height counter and repeat:
<script type="text/javascript">
var contentHeight = 4000,;
var pageHeight = document.documentElement.clientHeight;
var scrollPosition;
var n = 1;
function scroll(){
if(navigator.appName == "Microsoft Internet Explorer")
scrollPosition = document.documentElement.scrollTop;
else
scrollPosition = window.pageYOffset;
if((contentHeight - pageHeight - scrollPosition) < 500){
$.ajax({ url: "./yourAPI/?next="+n, cache: false,
success: function(data){
//append result
$('#infscroll').append('<div>'+data.result+'</div>');
}, dataType: "json"});
n += 1;
contentHeight += 4000;
}
}
$(document).scroll(function(){
setInterval('scroll();', 250);
});
</script>
<div id="infscroll"></div>
I have a function that gets individuals from the database and then, in jquery, runs through them, animating them. The problem...which I see is quite common is the fact that javascript runs through all the items in a split second and the delay would be applied to all.
I have search stackoverflow and have found some references to this, but none work with my code below. Any ideas would be greatly appreciated.
$individuals = $wpdb->get_results("SELECT * FROM wp_sisanda_individualsponsors");
?>
<script type="text/javascript">
function individual_sponsors() {
var individuals = <?php echo json_encode($individuals) ?>;
individuals.sort(function() { return 0.5 - Math.random() });
jQuery.each(individuals, function (i, elem) {
var topRand = Math.floor(Math.random()*301);
var leftRand = Math.floor(Math.random()*301);
var startLeftRand = Math.floor(Math.random()*301);
jQuery('.individuals').append('<div id="'+ elem.id + '" class="indiv" style="position: absolute; bottom: -70px; left:' + startLeftRand +'px;">' + elem.name + '</div>');
jQuery('#' + elem.id).animate({
top: -100,
left: Math.floor(Math.random()*301)
},20000 + Math.floor(Math.random()*50000));
});
}
</script>
As you can see, the items get a random horizontal starting position and ending position and a random speed, this works well, except there is still major bunching of items.
I have tried limiting the amount requested initially - randomly selecting a few and then calling the function repeatedly with a php wait in between, but this, I think, caused an ifinite loop...not sure...page wasn't loading.
I hope someone can point me in the right direction.
Ideally it would animate a few...wait...and then do some more...
Thanks in advance
A PHP wait won't help you as PHP executes on the server before anything gets sent to the client (where the JavaScript executes). If you want to animate a few, wait a bit, then animate some more, until you're done then you can use setTimeout:
var current = 0;
function animateSome() {
// Animate a few (starting at individuals[current]) and
// update current with the array index where you stopped.
// ...
// If there's anything left to do, start a timer to animate
// the next chunk of individuals.
if(current < individuals.length)
setTimeout(animateSome, 250);
}
animateSome();
I'm looking to create a simple jquery game.
It starts like this, the user enters a number in a text field.
<form>
<input type="text" id="MyNumber" value="" />
<button id="getit">Play</button>
</form>
<div id="randomnumber"></div>
After the click the play button, a series of numbers will appear in the div id randomnumber.
The objective is to click on the randomly rotating numbers in the div id randomnumber when they see the number they intered in the my number text field. If they click their number, they win.
The jquery script I have requires a button be pushed to generate the number, (I don't want a button pushed each time a new number should be generated.) The script also doesn't identify the number that was clicked, or send it to my checknumber.php page so I can store the number entered and the number picked in a database.
Any help?
this is the jquery script I have.
function IsNumeric(n){
return !isNaN(n);
}
$(function(){
$("#getit").click(function() {
var numLow = $("#lownumber").val();
var numHigh = $("#highnumber").val();
var adjustedHigh = (parseFloat(numHigh) - parseFloat(numLow)) + 1;
var numRand = Math.floor(Math.random()*adjustedHigh) + parseFloat(numLow);
if (IsNumeric(numLow)
&& IsNumeric(numHigh)
&& (parseFloat(numLow) <= parseFloat(numHigh))
&& (numLow != '')
&& (numHigh != ''))
{
$("#randomnumber").text(numRand);
} else {
$("#randomnumber").text("Careful now...");
}
return false;
});
$("input[type=text]").each(function(){
$(this).data("first-click", true);
});
$("input[type=text]").focus(function(){
if ($(this).data("first-click")) {
$(this).val("");
$(this).data("first-click", false);
$(this).css("color", "black");
}
});
});
The "Play" button is good to start the ball rolling (I'm not certain if you were thinking of removing it entirely). To generate numbers periodically, use setInterval.
$(function(){
var initialPeriod=500; // 0.5s
var generateNumIval;
function generateNum() {
var numLow = $("#lownumber").val();
var numHigh = $("#highnumber").val();
var adjustedHigh = (parseFloat(numHigh) - parseFloat(numLow)) + 1;
var numRand = Math.floor(Math.random()*adjustedHigh) + parseFloat(numLow);
if (IsNumeric(numLow)
&& IsNumeric(numHigh)
&& (parseFloat(numLow) <= parseFloat(numHigh))
&& (numLow != '')
&& (numHigh != ''))
{
$("#randomnumber").text(numRand);
} else {
$("#randomnumber").text("Careful now...");
}
}
function run(period) {
clearInterval(generateNumIval);
generateNumIval = setInterval(generateNum, period);
}
$("#getit").click(function() {
run(initialPeriod);
return false;
});
...
You can change the period (such as to increase the difficulty when the user clicks the correct number, or decreasing the difficulty when the user makes too many sequential mistakes) by calling run with a new period. If you want to change the period after generating each number, use setTimeout rather than setInterval.
To check a click on a number, register a click handler on #randomnumber that compares its val() to #MyNumber's val(). From there, take appropriate action as to whether it's a hit or miss. As Dan says, doing this for every click will create quite a bit of network traffic. Though only a small amount of data may be transmitted each time, the number of connections can cause a significant impact. Instead, have a "Stop" button and send the data if the user clicks it, or use an unload handler (one does not exclude the other).
Your server will crash and burn if you have more than a couple people playing this game. People can identify and click very fast (multiple times per second), but unless they live next to your server, you can't receive and respond to HTTP requests that fast, nor can your server handle hundreds or more per second from the multiple users.
Write the game in JavaScript and when they're done, send the totals (# of wrong clicks and # of right clicks, or whatever) to your server to save. Do your best to obfuscate how they're sent so that it's not trivial to make up scores.
There's a couple of things to look out for here. There's no reason why the random numbers can't be generated from the number the player has entered himself, or even better, a number generated by the game itself.
The way which you've done the placeholder text, using data and two event handlers is also somewhat messy. At a minimum you should be using .one to attach a one-time event handler for this, but it would be much better if you use the HTML5 placeholder attribute with a Javascript fallback.
Other than that, you're still missing significant amount of game logic in there. I won't advice you to work on this game for too long though - it's great as an exercise in working with JavaScript and jQuery, but otherwise not very worthwhile.
Oh, and just for fun, I also built my own version of this.
var hitCount = 0,
missCount = 0;
function IsNumeric(n) {
return !isNaN(n);
}
$("#getit").click(function() {
var li = [],
intervals = 0,
n = parseInt($('#MyNumber').val());
if (IsNumeric(n)) {
setInterval(function() {
li[intervals++ % li.length].text(Math.random() > .1 ? Math.floor(Math.random() * (10 + n) + (n / 2)) : n).attr('class', '');
}, 500);
}
$('#randomnumber').empty();
for (var i = 0; i < 5; i++) {
li.push($('<li />').click(function() {
var $this = $(this);
if (!$this.hasClass('clicked')) {
if (parseInt($this.text(), 10) === n) {
$this.addClass('correct');
$('#hitcount').text(++hitCount);
} else {
$this.addClass('wrong');
$('#misscount').text(++missCount);
}
}
$this.addClass('clicked');
}).appendTo('#randomnumber'));
}
return false;
});
Crude yes, but it sort of works. Have a look at it here: http://jsfiddle.net/DHPQT/
For fun..
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var mainLoop;
$(function(){
$("#getit").click(function() {
if ($(this).attr('class') == 'start') {
$(this).attr('class','play');
$(this).html('STOP THE MADNESS!');
mainLoop = window.setInterval(function() {
var output = '';
for (var i = 0; i < 10; i++) {
var numLow = $("#lownumber").val();
var numHigh = $("#highnumber").val();
var adjustedHigh = (parseFloat(numHigh) - parseFloat(numLow)) + 1;
var numRand = Math.floor(Math.random()*adjustedHigh) + parseFloat(numLow);
output += '<div>'+numRand+'</div>';
}
$('#randomnumbers').html(output);
},250);
} else {
window.clearInterval(mainLoop);
var sweetWin = false;
$('#randomnumbers').children().each(function() {
var v = $(this).html();
if (v == $('#MyNumber').val()) {
alert('WIN!');
sweetWin = true;
$.post('127.0.0.1',{outcome:'win'});
}
});
if (!sweetWin) {
alert('FAIL!');
$.post('127.0.0.1',{outcome:'loss'});
}
$(this).attr('class','start');
$(this).html('Play');
}
});
});
</script>
</head>
<body>
Low: <input type="text" id="lownumber" value="0" />
High: <input type="text" id="highnumber" value="100" />
<input type="text" id="MyNumber" value="50" />
<button id="getit" class="start">Play</button>
<div id="randomnumbers"></div>
</body>
</html>
I'm working on a GMaps application to retrieve images, via getJSON(), and to populate a popup marker.
The following is the markup which I add to the marker dynamically:
<div id="images"></div>
<div id="CampWindow" style="display:none;width:550px;height:500px;">
<h4 id="camp-title"></h4>
<p>View... (all links open in new windows)</p>
<ul>
<li><a id="camp-hp-link" target="_blank" href="">camp home page</a></li>
<li>information: <a id="camp-av-link" target="_blank" href="">availability</a> | <a id="camp-vi-link" target="_blank" href="">vital information</li>
</ul>
<p id="message"></p>
I've been clawing out my eyes and woohoo for the past couple of days, trying to get the images to show inside the CampWindow . Then, I decided to think laterally and to see if the images were being retrieved at all. I then moved the images outside and sure as Bob (Hope), the images were being retrieved and refreshed with every click.
So, I decided to the keep the images outside and then once loaded, append it to the CampWindow . It's not working still; when I append the div to the main CampWindow div, the images won't show. I check in Firebug with the pointer thingy and it shows me the images as empty. I try it again with the images outside and it shows the images. I've tried before append and appendTo with no success. Am I missing something here?
I have no more woohoo to claw out. Please, please help.
marker.clicked = function(marker){
$("#images").html('');
$('#camp-title').text(this.name);
$('#camp-hp-link').attr('href', this.url);
$('#camp-av-link').attr('href', this.url + '/tourism/availability.php');
$('#camp-vi-link').attr('href', this.url + '/tourism/general.php');
// get resort images via jQuery AJAX call - includes/GetResortImages.inc.php
$.getJSON('./includes/GetResortImages.inc.php', { park: this.park_name, camp: this.camp_name }, RetrieveImages);
function RetrieveImages (data)
{
if ('failed' == data.status)
{
$('#messages').append("<em>We don't have any images for this rest camp right now!</em>");
}
else
{
if ('' != data.camp)
{
$.each(data, function(key,value){
$("<img/>").attr("src", value).appendTo('#images');
});
}
}
}
//.append($("#images"));
$("#CampWindow").show();
var windowContent = $("<html />");
$("#CampWindow").appendTo(windowContent);
var infoWindowAnchor = marker.getIcon().infoWindowAnchor;
var iconAnchor = marker.getIcon().iconAnchor;
var offset = new google.maps.Size(infoWindowAnchor.x-iconAnchor.x,infoWindowAnchor.y-iconAnchor.y);
map.openInfoWindowHtml(marker.getLatLng(), windowContent.html(), {pixelOffset:offset});
}
markers.push(marker);
});
When you add the <html> tag to your page it confuses the browser and is most likely the problem. I would suggest to either do as Pointy said and use window.open() to make a popup window (check out this tutorial), or better yet try out one of the many jQuery light box plugins.
I'm not sure what you are doing with the google maps, so I decided to just go with a basic example for you. With this script, if you click on an image inside the #image div, it'll open a popup window the same size as the image.
$(document).ready(function(){
$('#images img').click(function(){
var padding = 20;
var w = $(this).width() + padding;
var h = $(this).height() + padding;
var popup = '\
<html>\
<head>\
<link type="text/css" href="popup-style.css" rel="stylesheet" />\
<scr'+'ipt type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></scr'+'ipt>\
</head>\
<body>\
<img src="' + $(this).attr('src') + '">\
</body>\
</html>';
var pop = window.open('','Image View','toolbar=0,location=0,status=0,width=' + w + ',height=' + h + ',scrollbars=1,resizable=1');
pop.document.write(popup);
pop.document.close();
})
});
NOTE: When adding a script tag inside a string, make sure you break up the word "script" otherwise you will get an error.
Update #2:
Ok, since you want to work with what you have, try doing this:
Remove the <html> tag from your campwindow, then position your campwindow using CSS and/or javascript. Add something like:
var w = $(window).width();
var h = $(window).height();
// Add overlay and make clickable to hide popup
// you can remove the background color and opacity if you want to make it invisible
var $overlay = $('<div/>', {
'id': 'overlay',
css: {
position : 'absolute',
height : h + 'px',
width : w + 'px',
left : 0,
top : 0,
background : '#000',
opacity : 0.5,
zIndex : 99
}
}).appendTo('body');
// Position your popup window in the viewport
$('#CampWindow').css({
position: 'absolute',
top : $(window).scrollTop() + 50 + 'px',
left : w/2 - $('#CampWindow').width()/2 + 'px', // centers the popup
zIndex : 100
})
.fadeIn('slow');
// Click overlay to hide popup
$('#overlay').click(function(){
$('#CampWindow').hide();
$(this).remove(); // remove the overlay
})