How to specify different delays between slides in bxslider - delay

Ran across the following problem in bxslider- how can you apply different delays between slides in the auto show?

I came up with the following solution which I will show here:
in the jquery.bxslider.js replace:
el.startAuto = function(preventControlUpdate){
// if an interval already exists, disregard call
if(slider.interval) return;
// create an interval
slider.interval = setInterval(function(){
slider.settings.autoDirection == 'next' ? el.goToNextSlide() : el.goToPrevSlide();
}, slider.settings.pause);
// if auto controls are displayed and preventControlUpdate is not true
if (slider.settings.autoControls && preventControlUpdate != true) updateAutoControls('stop');
}
With
/**EDITS: By CRB - techdude **/
el.startAuto = function(preventControlUpdate){
el.continueAuto();
}
el.continueAuto = function(){
//get how long the current slide should stay
var duration = slider.children.eq(parseInt(slider.active.index)).attr("duration");
if(duration == ""){
duration = slider.settings.pause;
} else {
duration = parseInt(duration);
}
console.log(duration);
// create a timeout
slider.timer = setTimeout(function(){
slider.settings.autoDirection == 'next' ? el.goToNextSlide() : el.goToPrevSlide();
el.continueAuto();
}, duration);
// if auto controls are displayed and preventControlUpdate is not true
if (slider.settings.autoControls && preventControlUpdate != true) updateAutoControls('stop');
}
//*End Edits*/
Then to change the duration of a slide, simply give its li tag a duration attribute like this:
where duration is the number of milliseconds for the slide to pause.
To set the default duration, simply use the pause: option in the settings:
$("element").bxSlider({
auto:true,
pause: 4000
};
Hope this helps. Maybe bx slider will even add it to a future version. :)

What are the you're using to pick this up? Any way you can put up a gist of it working?

Perhaps this will help clarify:
In principle, the way this works is I change the setInterval with a setTimeout so the interval can be changed each time.
The key to getting multiple elements to work on a page is to not use the slider.timer object, but probably to use the el.timer object so the line would read something like,
el.timer = setTimeout(function(){
slider.settings.autoDirection == 'next' ? el.goToNextSlide() : el.goToPrevSlide();
el.continueAuto();
}, duration);
Instead of
slider.timer = setTimeout(function(){
slider.settings.autoDirection == 'next' ? el.goToNextSlide() : el.goToPrevSlide();
el.continueAuto();
}, duration);
I haven't tested it with multiple sliders, but let me know if this works. That is the principle anyway. The only problem with this, however, is that I believe that you would need to modify the el.pause method to use the el.timer as well, otherwise the slideshow can't be paused. I think that was the reason I did it the way I did. However, it was a long time ago.

Related

Phaser 3 restarting tween with updated start values

I have 4 reusable tweens that should move the target relative to its current position.
Each of them is basically the same as this example one, but for each cardinal direction:
goLeft = this.tweens.add({
targets: gamePieceSprite,
x: {value: '-=64'},
duration: 1000,
paused: true
});
Since I want to be able to use these tweens multiple times, I use the restart() method, which I want to play the tween from the sprite's current position, but even when I change the position of the sprite, when I call the function to restart the tween it plays from the coordinates at which it first played and not where the targeted sprite currently is.
var pathCounter = 0;
testPathText.on('pointerdown', function(){
if (pathCounter % 2 == 0)
{
gamePieceSprite.setX(startTile.x);
gamePieceSprite.setY(startTile.y);
}
else
{
if (levelStartRotation[level] == '1')
{
goLeft.restart();
}
else if (levelStartRotation[level] == '2')
{
goUp.restart();
}
else if (levelStartRotation[level] == '3')
{
goDown.restart();
}
else if (levelStartRotation[level] == '4')
{
goRight.restart();
}
}
pathCounter++;
});
Is there any way for me to update the start point of the tween so that restarting it doesn't just start from where it started before?
I was also frustrated trying to figure this one out (and it looks like there still isn't a solution, almost one year later). I have not found any methods or best practices to do so yet, but by digging through the tween object, I discovered you can access the properties of a tween in its data array. Since it's an array, if you have multiple properties, you will have to find the property by comparing it's key value. If you only have one, simply get data[0]. The property has a start field that you can set.
In your case, try:
...
if (levelStartRotation[level] == '1')
{
goLeft.data[0].start = startTile.x;
goLeft.restart();
}
...

Make update loop in sync with music and notes in Phaser

I'm trying to make some notes appearing when the music hits a certain time in Phaser, but when I log the "hit times" in the console, it only show up sometimes.
I have an object of "notes", the key being the time I expect the note to show :
{
1377: {
jam: 1,
duration: 0.40
}
}
with 1464 notes.
But, in the update loop, if I do something like this :
update () {
if (music && music.currentTime) {
if (notes[music.currentTime]) {
console.log('notes[music.currentTime].jam', notes[music.currentTime].jam)
}
}
}
It logs only some of the notes, randomly.
Do you have any idea why ?
This is probably because music.currentTime is incrementing by ~16 ms on each update, so it can skip specific time keys from your notes object. Other than that I believe that the time can also be a floating point value, so it won't exactly match your keys in the notes variable.
An alternate way to implement what you want would be to change format of the notes variable to an array so it could be accessed later in a different manner:
var notes = [
...
{'start': 1377, 'jam': 1, 'duration': 0.40},
{'start': 2456, 'jam': 1, 'duration': 0.30},
...
];
// Index of the first note that will be played.
// Will be incremented by 1 or more with some update() calls,
// depending on the time that passed.
var nextNote = 0;
function update() {
// Process all notes that are now in the past
// compared to the current time of the playing music,
// but skip notes that have been already played before.
while (music && nextNote < notes.length && notes[nextNote].start <= music.currentTime) {
console.log(notes[nextNote]);
nextNote += 1;
}
}
For this method to work, the notes array must hold start times in an ascending order.

Bullet spawn speed or generation speed phaser

Hi all I have a function that generates bullets every time the player touches the screen.
Is there a way that I can limit the amount of bullets generated? Basically if I press the screen very quickly lots of bullets get generated but I would like to limit it to at least i per second instead of 2 or 3 per second.
Below you can find my firing function and my bullet creation function:
createBullets: function(){
//Bullets
this.bullets = this.add.group();
this.bullets.enableBody = true;
this.bullets.physicsBodyType = Phaser.Physics.P2JS;
this.bullets.createMultiple(500, 'bullet', 0, false);
this.bullets.setAll('anchor.x', 0.5);
this.bullets.setAll('anchor.y', 0.5);
this.bullets.setAll('outOfBoundsKill', true);
this.bullets.setAll('checkWorldBounds', true);
},
fireBullet: function(){
this.bullet = this.bullets.getFirstExists(false);
if (this.bullet) {
this.bullet.reset(this.tanque.x, this.tanque.y - 20);
this.bullet.body.velocity.y = -500;
}
},
and my update function:
if(this.input.activePointer.isDown){
if (!this.mouseTouchDown) {
this.touchDown();
}
}else {
if (this.mouseTouchDown) {
this.touchUp();
}
}
Any help I would really appreciate.
One option is to store two values:
nextShotTime: next time a shot can be fired
shotDelay: delay between shots (can be set like Phaser.Timer.SECOND * 2)
I don't see where you're calling fireBullet() in your example code above, but either before you make the call, or within the function, you could then check to see if the nextShotTime is in the past. If it is, fire another bullet and then update the nextShotTime with the current time plus the shotDelay.
For example:
if (this.nextShotTime < this.time.now) {
this.nextShotTime = this.time.now + this.shotDelay;
// add your code that will fire a bullet.
}
I have had similar problems in games before. The solution I used is the same as the one posted above. I found it in this
Phaser tutorial.
The fire function used in the tutorial is:
fire: function() {
if (this.nextShotAt > this.time.now) {
return;
}
this.nextShotAt = this.time.now + this.shotDelay;
You can modify it to suit your purposes.
This is part of a fire function I used in a game I made:
fire: function() {
//Make sure the player can't shoot when dead and that they are able to shoot another bullet
if(!this.player.alive || this.time.now < this.nextFireTime) {
return;
}
this.nextFireTime = this.time.now + this.fireRate;
var bullet;
//If weaponlvl = 0, shoot a normal bullet
if(this.weaponlvl === 0) {
if(this.bullet1.countDead() === 0) {
return;
}
//Properties for the basic weapon
this.fireRate = 500;
bullet = this.bullet1.getFirstExists(false);
bullet.reset(this.player.x, this.player.y-22);
bullet.body.velocity.y = -300;
}
Hope this helps you in some way.

Option issue using chrome.storage.sync.get for first time user

chrome.storage.sync.get('savedItem', function (result) {
//some if else condition for result.savedItem here
myResult = result.savedItem;
});
$('p').val(myResult);
With above code, I got an undefined, because there is no setting been saved in my options page for the first time user. I tried to set a default value to myResult like if(result.savedItem == undefined) myResult = ''; but I still got undefined. Why?
2 issues at the same time.
1) You can set default for values not in the storage by providing a dictionary:
chrome.storage.sync.get({'savedItem' : 'myDefault'}, function (result) {
// result.savedItem is the saved value or 'myDefault'
});
2) The biggest issue is not understanding how asynchronous code works.
$('p').val(myResult); gets executed before myResult is assigned, because chrome.storage.sync.get returns immediately, with the function(result){...} being called later.
There have been tons of questions about that, take a look at, say, this and this.
Use chrome storage change - Refer this link
Example code:
chrome.storage.onChanged.addListener(function(changes, namespace) {
for (var key in changes) {
var storageChange = changes[key];
console.log('Storage key "%s" in namespace "%s" changed. ' + 'Old value was "%s", new value is "%s".', key, namespace, storageChange.oldValue, storageChange.newValue);
}
});

Preventing tab to cycle through address bar

I realize this is probably an accessibility issue that may best be left alone, but I'd like to figure out if it possible to prevent the tab from visiting the address bar in the tabbing cycle.
My application has another method of cycling through input areas, but many new users instinctively try to use the tab, and it doesn't work as expected.
Here's a generic jquery implementation where you don't have to find the max tab index. Note that this code will also work if you add or remove elements in your DOM.
$('body').on('keydown', function (e) {
var jqTarget = $(e.target);
if (e.keyCode == 9) {
var jqVisibleInputs = $(':input:visible');
var jqFirst = jqVisibleInputs.first();
var jqLast = jqVisibleInputs.last();
if (!e.shiftKey && jqTarget.is(jqLast)) {
e.preventDefault();
jqFirst.focus();
} else if (e.shiftKey && jqTarget.is(jqFirst)) {
e.preventDefault();
jqLast.focus();
}
}
});
However, you should note that the code above will work only with visible inputs. Some elements may become the document's activeElement even if they're not input so if it's your case, you should consider adding them to the $(':input:visible') selector.
I didn't add code to scroll to the focus element as this may not be the wanted behavior for everyone... if you need it, just add it after the call to focus()
You can control the tabbing order (and which elements should be able to get focus at all) with the global tabindex attribute.
However, you can't prevent users to tab into another context not under control of the page (e.g. the browser's address bar) with this attribute. (It might be possible in combination with JavaScript, though.)
For such a (evil!) use case, you'd have to look into keyboard traps.
WCAG 2.0 has the guideline: 2.1.2 No Keyboard Trap. In Understanding SC 2.1.2 you can find "Techniques and Failures" for this guideline:
F10: Failure of Success Criterion 2.1.2 and Conformance Requirement 5 due to combining multiple content formats in a way that traps users inside one format type
FLASH17: Providing keyboard access to a Flash object and avoiding a keyboard trap
G21: Ensuring that users are not trapped in content
So maybe you get some ideas by that how such a trap would be possible.
I used to add two tiny, invisible elements on tabindex 1 and on the last tabindex. Add a onFocus for these two: The element with tabindex 1 should focus the last real element, the one with the max tabindex should focus the first real element. Make sure that you focus the first real element on Dom:loaded.
You could use Javascript and capture the "keydown" event on the element with the highest "tabindex". If the user presses the "TAB" key (event.keyCode==9) without the "Shift" key (event.shiftKey == false) then simply set the focus on the element with the lowest tabindex.
You would then also need to do the same thing in reverse for the element with the lowest tabindex. Capture the "keydown" event for this element. If the user presses the "TAB" key (event.keyCode==9) WITH the "Shift" key (event.shiftKey == true) then set the focus on the element with the highest tabindex.
This would effectively prevent the address bar from ever being focused using the TAB key. I am using this technique in my current project.
Dont forget to cancel the keydown event if the proper key-combination is pressed! With JQuery it's "event.preventDefault()". In standard Javascript, I believe you simply "return false".
Here's a JQuery-laden snippet I'm using...
$('#dos-area [tabindex=' + maxTabIndex + ']').on('keydown', function (e) {
if (e.keyCode == 9 && e.shiftKey == false) {
e.preventDefault();
$('#dos-area [tabindex=1]').focus();
}
});
$('#dos-area [tabindex=1]').on('keydown', function (e) {
if (e.keyCode == 9 && e.shiftKey == true) {
e.preventDefault();
$('#dos-area [tabindex=' + maxTabIndex + ']').focus();
}
});
Also keep in mind that setting tabindex=0 has undesirable results on the order in which things are focused. I always remember (for my purposes) that tabindex is a 1-based index.
Hi i have an easy solution. just place an empty span on the end of the page. Give it an id and tabindex = 0, give this span an onfocus event, when triggered let your focus jump to the first element on your page you want to cycle trough. This way you won't lose focus on the document, because if you do your events don't work anymore.
I used m-albert solution and it works. But in my case I do not control the tabindex properties. My intention is set the focus on a toolbar at the top of the page (first control) when user leaves the last control on the page.
$(':input:visible').last().on('keydown', function (e) {
if (e.keyCode == 9 && e.shiftKey == false) {
e.preventDefault();
$('html, body').animate({
scrollTop: 0
}, 500);
$(':input:visible', context).first().focus();
}
});
Where context can be any Jquery object, selector, or even document, or you can omit it.
The scrolling animation, of course, is optional.
Not sure if this is still a issue, but I implemented my own solution that does not use jQuery, can be used in the case when all the elements have tabindex="0", and when the DOM is subject to change. I added an extra argument for a context if you want to limit the tabcycling to a specific element containing the tabindex elements.
Some brief notes on the arguments:
min must be less than or equal to max, and contextSelector is an optional string that if used should be a valid selector. If contextSelector is an invalid selector or a selector that doesn't match with any elements, then the document object is used as the context.
function PreventAddressBarTabCyle(min, max, contextSelector) {
if( isNaN(min) ) throw new Error('Invalid argument: first argument needs to be a number type.')
if( isNaN(max) ) throw new Error('Invalid argument: second argument needs to be a number type.')
if( max < min ) throw new Error('Invalid arguments: first argument needs to be less than or equal to the second argument.')
min = min |0;
max = max |0;
var isDocumentContext = typeof(contextSelector) != 'string' || contextSelector == '';
if( min == max ) {
var tabCycleListener = function(e) {
if( e.keyCode != 9 ) return;
var context = isDocumentContext ? document : document.querySelector(contextSelector);
if( !context && !('querySelectorAll' in context) ) {
context = document;
}
var tabindexElements = context.querySelectorAll('[tabindex]');
if( tabindexElements.length <= 0 ) return;
var targetIndex = -1;
for(var i = 0; i < tabindexElements.length; i++) {
if( e.target == tabindexElements[i] ) {
targetIndex = i;
break;
}
}
// Check if tabbing backward and reached first element
if( e.shiftKey == true && targetIndex == 0 ) {
e.preventDefault();
tabindexElements[tabindexElements.length-1].focus();
}
// Check if tabbing forward and reached last element
if( e.shiftKey == false && targetIndex == tabindexElements.length-1 ) {
e.preventDefault();
tabindexElements[0].focus();
}
};
} else {
var tabCycleListener = function(e) {
if( e.keyCode != 9 ) return;
var context = isDocumentContext ? document : document.querySelector(contextSelector);
if( !context && !('querySelectorAll' in context) ) {
context = document;
}
var tabindex = parseInt(e.target.getAttribute('tabindex'));
if( isNaN(tabindex) ) return;
// Check if tabbing backward and reached first element
if (e.shiftKey == true && tabindex == min) {
e.preventDefault();
context.querySelector('[tabindex="' + max + '"]').focus();
}
// Check if tabbing forward and reached last element
else if (e.shiftKey == false && tabindex == max) {
e.preventDefault();
context.querySelector('[tabindex="' + min + '"]').focus();
}
};
}
document.body.addEventListener('keydown', tabCycleListener, true);
}
More notes:
If min is equal to max, then tab cycling will occur naturally until the last element in the context is reached. If min is strictly less than max, then tabbing will cycle naturally until either the min or the max is reached. If tabbing backwards and the min is reached, or tabbing forward and the max is reached, then the tabbing will cycle to the min element or max element respectively.
Example usage:
// For all tabindex elements inside the document
PreventAddressBarTabCyle(0,0);
// Same as above
PreventAddressBarTabCyle(1,1);
// NOTE: if min == max, the tabindex value doesn't matter
// it matches all elements with the tabindex attribute
// For all tabindex elements between 1 and 15
PreventAddressBarTabCyle(1,15);
// For tabindex elements between 1 and 15 inside
// the first element that matches the selector: .some-form
PreventAddressBarTabCyle(1,15, '.some-form');
// For all tabindex elements inside the element
// that matches the selector: .some-form2
PreventAddressBarTabCyle(1,1, '.some-form2');
Salinan solution worked for me
Put this in the start of your html page:
<span tabindex="0" id="prevent-outside-tab"></span>
and this at the end of your html page.:
<span tabindex="0" onfocus="foucsFirstElement()"></span>
foucsFirstElement() :
foucsFirstElement() {
document.getElementById("prevent-outside-tab").focus();
},

Resources