So I think I am doing everything correct with my jquery mobile slider, but the control is not being re-enabled. I've made a pretty decent jsFiddle with it, in hopes someone will spot the error quickly.
On the fiddle you will see the jQuery moblie control. If you click and move the slider position the event will fire that the control value changed. If you end up changing the value more than 5 times within 20 seconds the control will lock up. You can think of this as being a cooldown period. Well after the control cools down it should be re-enabled for more mashing.
Problem is, the control never comes back from being disabled!
http://jsfiddle.net/Narq6/
Sample Javascript:
var sent = 0;
var disabled = false;
$('#slider-fill').on( 'slidestop', function()
{
send();
writeConsole(sent);
})
function send()
{
setTimeout(decrease, 4000);
sent +=1;
if(sent > 5)
{
$('#slider-fill').prop('disabled', 'disabled');
disabled = true;
}
}
function decrease()
{
if(sent > 0)
sent -= 1;
writeConsole('decrease');
writeConsole(sent);
if(sent === 0)
{
//CODE TO DISABLE HERE!!!
//LOOK HERE THIS IS WHERE I REMOVE THE DISABLE!!!
writeConsole('no longer disabled!');
$('#slider-fill').prop('disabled', '');
///YOU LOOKED TOO FAR GO BACK A LITTLE BIT :D
}
}
function writeConsole(message)
{
var miniconsole = $('#miniConsole');
var contents = miniconsole.html();
miniconsole.html(contents + message + '<br/>' );
miniconsole.scrollTop(10000);
}
You were using incorrect enable/disable syntax.
This one is a coorect syntax:
$('#slider-fill').slider('disable');
and
$('#slider-fill').slider('enable');
Here's am working example made from your jsFiddle: http://jsfiddle.net/Gajotres/djDDr/
Related
I've been making a game to practice programming, and I am having trouble using the Jquery .click() function. I have two buttons in my code, the start button and the attack button. When I click the start button, the .click() function fires the code for the other button as well, which causes my main menu to freeze up and not draw the game screen. I've used separate id's for the buttons, but they both seem to recognize the click on the start button. I can't get it to work in JSFiddle, but all the code is there. Can someone please tell me how to use multiple buttons?
//start button
$('#startButton').click(function() {
stage.state = "battle";
stage.update();
})
//attack button
$('#attack').click(firstTurn());
//attack button code
function firstTurn() {
console.log("firstTurn Fired");
if(p1.speed > opp.speed){
turn = 1;
} else{
turn = 0;
}
battle();
};
function battle(){
var battling = 1;
while(battling == 1) {
if(turn == 0) {
p1.health = p1.health-opp.attack;
$("#textBox").append('<p>'+opp.name+' hit you for '+ opp.attack+' points.</p><br/>');
draw();
sleep(1000);
console.log("attacked");
} else{
opp.health = opp.health-p1.attack;
$('#textBox').append('<p> You hit '+opp.name+' for '+p1.attack+' points.</p><br/>');
draw();
sleep(1000);
}
}
};
https://jsfiddle.net/memersond/m3gvv8y6/
$('#attack').click(firstTurn());
Should be:
$('#attack').click(firstTurn);
You want to pass the function as a reference, not have it executed immediately.
$('#attack').click(firstTurn());
This causes firstTurn() to be called when the listener is initiated, use one of the alternatives:
$('#attack').click(firstTurn );
$('#attack').click(function() {
firstTurn()
});
I am trying to implement kind of player on my website.
If press 'Play' button, the music starts and the page smoothly scrolls down.
But when you press 'Mute' button (function(){music.volume=0}) I am not sure why the page appears at the top again. window.scroll() doesn't do anything without delay. So i am using setTimeout function to scroll the page on the current place. The problem is that in Opera and IE setTimeout takes about 10 ms, so when i click 'Mute' button i see like ticks to top and back. In chrome it takes only 2 ms and there is no problems.
Now when i decide to create my own timeout function the window.scroll() does not work again.
Here is my code:
var isMuted = false;
muteButton.onclick = function() { ////This function works with big delay.
if (!isMuted) {
mainAudio.volume = 0;
isMuted = true;
} else {
mainAudio.volume = bgAudioTrackVolume;
isMuted = false;
}
setTimeout(function() {
window.scroll(0, offset); /// Works
}, 0)
};
Change setTimeout with:
i = 9542155.873; /// I have tried delay time from 1ms - 250ms by changing this value.
while (i > 0.00001) {
i = i / 1.0001234567;
if (i < 0.00001) {
window.scroll(0, offset); /// Does not do anything. Strange! Have tried to change variable with a number.
}
}
Every time i check offset value, it is always available before calling scroll function.
I know that my problem is not usual and i am realy need your help.
The reason that the page scrolls to the top is that you are using a link with the empty bookmark #, which represents the top of the page. The reason that the scroll method doesn't work without a timeout is that jumping to the bookmark happens after the event handler.
Instead of trying to scroll the page back to where it was, just stop the default action of the link by returning false from the event handler:
var isMuted = false;
muteButton.onclick = function() {
if (!isMuted) {
mainAudio.volume = 0;
isMuted = true;
} else {
mainAudio.volume = bgAudioTrackVolume;
isMuted = false;
}
return false;
};
Alternatively, use some other element than a link.
Could someone please share experience / code how we can detect the browser back button click (for any type of browsers)?
We need to cater all browser that doesn't support HTML5
The 'popstate' event only works when you push something before. So you have to do something like this:
jQuery(document).ready(function($) {
if (window.history && window.history.pushState) {
window.history.pushState('forward', null, './#forward');
$(window).on('popstate', function() {
alert('Back button was pressed.');
});
}
});
For browser backward compatibility I recommend: history.js
In javascript, navigation type 2 means browser's back or forward button clicked and the browser is actually taking content from cache.
if(performance.navigation.type == 2) {
//Do your code here
}
there are a lot of ways how you can detect if user has clicked on the Back button. But everything depends on what your needs. Try to explore links below, they should help you.
Detect if user pressed "Back" button on current page:
Is there a way using Jquery to detect the back button being pressed cross browsers
detect back button click in browser
Detect if current page is visited after pressing "Back" button on previous("Forward") page:
Is there a cross-browser onload event when clicking the back button?
trigger event on browser back button click
Found this to work well cross browser and mobile back_button_override.js .
(Added a timer for safari 5.0)
// managage back button click (and backspace)
var count = 0; // needed for safari
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("back", null, null);
window.onpopstate = function () {
history.pushState('back', null, null);
if(count == 1){window.location = 'your url';}
};
}
}
setTimeout(function(){count = 1;},200);
In case of HTML5 this will do the trick
window.onpopstate = function() {
alert("clicked back button");
}; history.pushState({}, '');
You can use this awesome plugin
https://github.com/ianrogren/jquery-backDetect
All you need to do is to write this code
$(window).load(function(){
$('body').backDetect(function(){
// Callback function
alert("Look forward to the future, not the past!");
});
});
Best
In my case I am using jQuery .load() to update DIVs in a SPA (single page [web] app) .
Being new to working with $(window).on('hashchange', ..) event listener , this one proved challenging and took a bit to hack on. Thanks to reading a lot of answers and trying different variations, finally figured out how to make it work in the following manner. Far as I can tell, it is looking stable so far.
In summary - there is the variable globalCurrentHash that should be set each time you load a view.
Then when $(window).on('hashchange', ..) event listener runs, it checks the following:
If location.hash has the same value, it means Going Forward
If location.hash has different value, it means Going Back
I realize using global vars isn't the most elegant solution, but doing things OO in JS seems tricky to me so far. Suggestions for improvement/refinement certainly appreciated
Set Up:
Define a global var :
var globalCurrentHash = null;
When calling .load() to update the DIV, update the global var as well :
function loadMenuSelection(hrefVal) {
$('#layout_main').load(nextView);
globalCurrentHash = hrefVal;
}
On page ready, set up the listener to check the global var to see if Back Button is being pressed:
$(document).ready(function(){
$(window).on('hashchange', function(){
console.log( 'location.hash: ' + location.hash );
console.log( 'globalCurrentHash: ' + globalCurrentHash );
if (location.hash == globalCurrentHash) {
console.log( 'Going fwd' );
}
else {
console.log( 'Going Back' );
loadMenuSelection(location.hash);
}
});
});
It's available in the HTML5 History API. The event is called 'popstate'
Disable the url button by following function
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload for this.
};
}
else {
var ignoreHashChange = true;
window.onhashchange = function () {
if (!ignoreHashChange) {
ignoreHashChange = true;
window.location.hash = Math.random();
// Detect and redirect change here
// Works in older FF and IE9
// * it does mess with your hash symbol (anchor?) pound sign
// delimiter on the end of the URL
}
else {
ignoreHashChange = false;
}
};
}
};
Hasan Badshah's answer worked for me, but the method is slated to be deprecated and may be problematic for others going forward. Following the MDN web docs on alternative methods, I landed here: PerformanceNavigationTiming.type
if (performance.getEntriesByType("navigation")[0].type === 'back_forward') {
// back or forward button functionality
}
This doesn't directly solve for back button over the forward button, but was good enough for what I needed. In the docs they detail the available event data that may be helpful with solving your specific needs:
function print_nav_timing_data() {
// Use getEntriesByType() to just get the "navigation" events
var perfEntries = performance.getEntriesByType("navigation");
for (var i=0; i < perfEntries.length; i++) {
console.log("= Navigation entry[" + i + "]");
var p = perfEntries[i];
// dom Properties
console.log("DOM content loaded = " + (p.domContentLoadedEventEnd -
p.domContentLoadedEventStart));
console.log("DOM complete = " + p.domComplete);
console.log("DOM interactive = " + p.interactive);
// document load and unload time
console.log("document load = " + (p.loadEventEnd - p.loadEventStart));
console.log("document unload = " + (p.unloadEventEnd -
p.unloadEventStart));
// other properties
console.log("type = " + p.type);
console.log("redirectCount = " + p.redirectCount);
}
}
According to the Docs at the time of this post it is still in a working draft state and is not supported in IE or Safari, but that may change by the time it is finished. Check the Docs for updates.
suppose you have a button:
<button onclick="backBtn();">Back...</button>
Here the code of the backBtn method:
function backBtn(){
parent.history.back();
return false;
}
I want that when a user clicks on any external link (identified by either particular id or class) on my site then he should get a popup with a counter of 10 seconds, after 10 seconds the popup should close and the user should be able to access the external URL. How can this be done? I'm able to show a warning like below but I don't know how to add timeout to it, also this is a confirm box, not a popup where I can add some div and more stuff for user to see until the counter stops.
$(document).ready(function(){
var root = new RegExp(location.host);
$('a').each(function(){
if(root.test($(this).attr('href'))){
$(this).addClass('local');
}
else{
// a link that does not contain the current host
var url = $(this).attr('href');
if(url.length > 1)
{
$(this).addClass('external');
}
}
});
$('a.external').live('click', function(e){
e.preventDefault();
var answer = confirm("You are about to leave the website and view the content of an external website. We cannot be held responsible for the content of external websites.");
if (answer){
window.location = $(this).attr('href');
}
});
});
PS: Is there any free plugin for this?
I've put together a little demo to help you out. First thing to be aware of is your going to need to make use of the setTimeout function in JavaScript. Secondly, the confirmation boxes and alert windows will not give you the flexibility you need. So here's my HTML first I show a simple link and then created a popup div that will be hidden from the users view.
<a href='http://www.google.com'>Google</a>
<div id='popUp' style='display:none; border:1px solid black;'>
<span>You will be redirected in</span>
<span class='counter'>10</span>
<span>Seconds</span>
<button class='cancel'>Cancel</button>
</div>
Next I created an object that controls how the popup is displayed, and related events are handled within your popup. This mostly is done to keep my popup code in one place and all events centrally located within the object.
$('a').live('click', function(e){
e.preventDefault();
popUp.start(this);
});
$('.cancel').click(function()
{
popUp.cancel();
});
var popUp = (function()
{
var count = 10; //number of seconds to pause
var cancelled = false;
var start = function(caller)
{
$('#popUp').show();
timer(caller);
};
var timer = function(caller)
{
if(cancelled != true)
{
if(count == 0)
{
finished(caller);
}
else
{
count--;
$('.counter').html(count);
setTimeout(function()
{
timer(caller);
}, 1000);
}
}
};
var cancel = function()
{
cancelled = true;
$('#popUp').hide();
}
var finished = function(caller)
{
alert('Open window to ' + caller.href);
};
return {
start : start,
cancel: cancel
};
}());
If you run, you will see the popup is displayed and the countdown is properly counting down. There's still some tweaks of course that it needs, but you should be able to see the overall idea of whats being accomplished. Hope it helps!
JS Fiddle Sample: http://jsfiddle.net/u39cV/
You cannot using a confirm native dialog box as this kind of dialog, as alert(), is blocking all script execution. You have to use a cutomized dialog box non-blocking.
You can use for example: jquery UI dialog
Even this has modal option, this is not UI blocking.
Consdier using the javascript setTimeout function to execute an action after a given delay
if (answer){
setTimeOut(function(){
//action executed after the delay
window.location = $(this).attr('href');
}, 10000); //delay in ms
}
I recently fixed a prob I had with the sliding field thanks to you so I wanted to ask this problem too.
On the site: http://www.trulyscience.com/test/index.html I have a little box with questions. It slides open when you press it and slides shut when your press again.
Now my problem is that this does not work in IE.
Here is the code:
function loadQuestion(){
var lol;
lol = 1;
jQuery('#question').click(function(){
if (lol==0){
jQuery('#question').animate({height:'300'});
lol = 1;
}else{
jQuery('#question').animate({height:'30'});
lol = 0;
}
});
jQuery('#question').trigger('click'); // Simulating click
}
jQuery(document).ready(function(){
loadQuestion();
});
I think you have a problem with calling loadQuestion() before the question div is available to jQuery, so the click event is never added.
I added a breakpoint and a watch in the ready function which seemed to indicate this at least.
jQuery(document).ready(function(){
// does this print 0 in IE?
console.log(jQuery('#question').length);
loadQuestion();
});
Just to verify you could move the script to the bottom of the page and see if that solves the problem. If it does, I would still investigate why the question div is not available when document ready triggers in IE.
function loadQuestion(){
var lol;
lol = 1;
var invalidElems = {
INPUT : true,
TEXTAREA : true
};
jQuery('#question').click(function(e){
if(e.target.tagName in invalidElems === false){
if (lol==0){
jQuery('#question').animate({height:'300'});
lol = 1;
}else{
jQuery('#question').animate({height:'30'});
lol = 0;
}
}
});
jQuery('#question').trigger('click'); // Simulating click
}
jQuery(document).ready(function(){
loadQuestion();
});
Demo