How to turn music on and off with one button? - javascript

For my website I use the ION.sound plugin and i would like to pause a fragment and play it again with the same button. Unfortunately, Jquery's .toggle has been removed in version 1.9 and can not be used anymore. How could I turn this audiofragment on and off with the same button? This is what i have so far:
$.ionSound({
sounds: [
"track_radio"
],
path: "sounds/",
multiPlay: true,
volume: "0.8"
});
playRadio = function() {
$.ionSound.play("track_radio");
}
stopRadio = function() {
$.ionSound.stop("track_radio");
}
$("#speakers").click(function(event){
playRadio();
});

You need something to track the playing status and check it when clicked.
$.ionSound({
sounds: [
"track_radio"
],
path: "sounds/",
multiPlay: true,
volume: "0.8",
playing: false;
});
onOffRadio = function() {
$.ionSound.play("track_radio");
$.ionSound.playing = true;
}
stopRadio = function() {
$.ionSound.stop("track_radio");
$.ionSound.playing = false;
}
$("#speakers").click(function(event){
if ($.ionSound.playing) {
stopRadio();
}
else {
playRadio();
}
});

You can simply make use of the 'text' attribute of the button element.
<button id="play-pause">Play</button>
$("#play-pause").click(function() {
if($(this).text() == 'Play') {
playRadio();
$(this).text('Pause');
}
else {
pauseRadio();
$(this).text('Play');
}
});
Here's the fiddle

Related

What is the best way to shorten this code?

Using the DRY methodology, I was wondering what could be the best way this code could be shorten. It seems to me there is too much repetition in there.
function back(){
$('.back').click(function(){
if($(this).hasClass('back_3')){
$('.screen3').addClass('hidden');
$('.screen1').removeClass('hidden');
}else if ($(this).hasClass('back_2')){
$('.screen2').addClass('hidden');
$('.screen1').removeClass('hidden');
}else if($(this).hasClass('back_4')){
$('.screen4').addClass('hidden');
$('.screen3').removeClass('hidden');
}else if($(this).hasClass('back_5')){
$('.screen5').addClass('hidden');
$('.screen3').removeClass('hidden');
}else if($(this).hasClass('back_6')){
$('.screen6').addClass('hidden');
$('.screen3').removeClass('hidden');
}
});
}
Best way to DRYify this code is to use data-* attributes to link the button to what to hide/show
eg (for first if branch)
<button class="back" data-hide=".screen3" data-show=".screen1">Back_3</button>
and then this
$('.back').click(function(){
var $this = $(this);
$($this.data("hide")).addClass("hidden");
$($this.data("show")).removeClass("hidden");
});
Same handler works for any .back button with data-hide and data-show attributes.
Simpy extract the id of the class, then hide/show the respective classes:
$('.back').click(function(){
var id = this.className.split(" ").find(clss => clss.includes("back_")).split("_")[1];
$(".screen"+id).addClass("hidden");
$(".screen"+id>3?3:1).removeClass("hidden");
});
I would do something like this (not tested):
var arrScreens=[
{hC:"back_3",screenShow:".screen3",screenHide:".screen1"]},
{hC:"back_2",screenShow:".screen2",screenHide:".screen1"]},
]
function back(){
$('.back').click(function(){
var $this=$(this);
$(arrScreens).each(function(i,obj) {
if($this.hasClass(obj.hC)) {
$(obj.screenShow).addClass('hidden');
$(obj.screenHide).removeClass('hidden');
return false;
}
});
});
}
This is what I would have done in your case.
const routes = [
{id: 'back_3', hide: '.screen3', show: '.screen1' },
{id: 'back_2', hide: '.screen2', show: '.screen1' },
{id: 'back_4', hide: '.screen4', show: '.screen3' },
{id: 'back_5', hide: '.screen5', show: '.screen3' },
{id: 'back_6', hide: '.screen6', show: '.screen3' },
];
function back() {
const hiddenCls = 'hidden';
const $back = $('.back');
return $back.click(event => {
event.preventDefault();
for(const route of routes) {
const {id, hide, show} = route;
if($(event.currentTarget).hasClass(id)) {
$(hide).addClass(hiddenCls);
$(show).removeClass(hiddenCls);
break;
}
}
});
}

Play and Pause in BookBlock.js

How to create play and pause functionality in bookblock.js.
below is my js function which is invoked on click of play/pause button.
i am not able to pause(and again recycle) the slideshow using this function. what is wrong in this.
function playPauseSlide(obj) {
if (isPlay) {
$(obj).find('i').removeClass('glyphicon-pause').addClass('glyphicon-play');
$('#bb-bookblock').bookblock({ autoplay: false });
} else {
$(obj).find('i').removeClass('glyphicon-play').addClass('glyphicon-pause');
$('#bb-bookblock').bookblock({ autoplay: true, interval: 1000 });
}
isPlay = !isPlay;
}
after lots of trying i finally added play and pause functions in slide show by customizing the script.
jquery.bookblock.js
_pauseSlideshow: function () {
if ( this.options.autoplay ) {
clearTimeout( this.slideshow );
}
},
//// public method: pause the slide show
pause: function () {
this._pauseSlideshow();
},
//// public method: play again the paused slide show
playAgain: function () {
this.options.autoplay = true;
this._navigate('next', this.$currentItem);
this._startSlideshow();
},
In my view script
var config = {
$bookBlock: $('#bb-bookblock'),
$navNext: $('#nextPage'),
$navPrev: $('#prevPage'),
$navFirst: $('#bb-nav-first'),
$navLast: $('#bb-nav-last'),
$pause: $('#pause'),
$playAgain: $('#playAgain'),
},
initEvents = function () {
config.$pause.on('click touchstart', function () {
config.$bookBlock.bookblock('pause');
return false;
});
config.$playAgain.on('click touchstart', function () {
config.$bookBlock.bookblock('playAgain');
return false;
});
});

return true for click event and continue

Hi I have a popup window control what I'm trying todo is get it to continue the click event if the user chooses the yes button. How do you continue the click event for the 'yes' button, I'm trying to make it return true but it doesn't continue for the click it just return false.
<script type="text/javascript">
$(document).ready(function() {
$('.delete-question').click(function(e) {
ret = false;
_this = this;
$('#pop-up-1').popUpWindow({
modal: true,
blurClass: '.main-container',
action: "open",
buttons: [{
text: "Yes",
click: function () {
this.close();
ret = true;
}
}, {
text: "No",
click: function () {
this.close();
}
}]
});
return ret;
})
});
</script>
You can't do it directly, but you can emit the click event once it is needed, e.g. something like this (not tested):
<script type="text/javascript">
// global flag to track the popup state
var popupReturn = false;
$(document).ready(function() {
$('.delete-question').click(function(e) {
// when true (after Yes click only) go on returning true
if (popupReturn) {
popupReturn = false;
return true;
}
else {
_this = this;
$('#pop-up-1').popUpWindow({
modal: true,
blurClass: '.main-container',
action: "open",
buttons: [{
text: "Yes",
click: function () {
// set global flag to true
popupReturn = true;
// emit click event where it knows that popupReturn is true
$(_this).click();
this.close();
}
}, {
text: "No",
click: function () {
this.close();
}
}]
});
return false;
}
})
});
</script>
You can't return from asynchronous event like in your case, because your "modal" is not really modal in sense that it doesn't pause code execution until use clicks a button.
This is where callback come handy. I would wrap the modal code into helper plugin and use it like this:
$.fn.confirmable = function(options) {
options = $.extend({
close: $.noop,
dismiss: $.noop
}, options);
this.each(function() {
$(this).popUpWindow({
modal: true,
blurClass: '.main-container',
action: "open",
buttons: [{
text: "Yes",
click: function() {
this.close();
options.close();
}
}, {
text: "No",
click: function() {
this.close();
options.dismiss();
}
}]
});
});
};
$('.delete-question').confirmable({
close: function() {
// ok pressed do something
},
dismiss: function() {
// cancel pressed
}
});
It means that your workflow needs to transform to asynchronous callback/promise-based.

To apply .delay() on mouseenter in my plugin

I got a div, that on mouseenter, is suppose to show another div. I'm not sure how to achive this in a plugin. This is my code and what I have tried so far.
Code: JsFiddle
<div class="hover-me"></div>
<div class="show-me"></div>
var Nav = {
hover_me: $('.hover-me'),
show_me: $('.show-me'),
init: function() {
Nav.toggle_display();
console.log('init');
},
toggle_display: function() {
Nav.hover_me.mouseenter(function() {
Nav.show();
});
Nav.hover_me.mouseleave(function () {
Nav.hide();
});
},
show: function() {
Nav.show_me.fadeIn();
},
hide: function() {
Nav.show_me.fadeOut();
}
};
I tried to do this, without any luck.
Nav.hover_me.mouseenter(function() {
Nav.delay(1000).show();
});
see Jimbo's comment:
var Nav = {
// [...]
timeoutId: undefined,
// [...]
};
Nav.hover_me.mouseenter(function() {
Nav.timeoutId = setTimeout(function() {
Nav.show();
}, 1000);
});
Nav.hover_me.mouseleave(function () {
if (Nav.timeoutId) { clearTimeout(Nav.timeoutId); }
Nav.hide();
});
SEE THE FIDDLE

unable to auto slide html pages using sencha

i am create simple app using sencha touch 2 + java script + html 5 which change / slide html pages automatically.
i write below code to slide html pages using DelayedTask task but the code is not working .
Main.js
Ext.create('Ext.Carousel', {
fullscreen: true,
xtype:'carousel',
cls:'carousel',
defaults: {
styleHtmlContent: true
},
config: {
ui : 'light',
},
listeners:
{
'afterrender': function(carousel) {
carousel.pageTurner = new Ext.util.DelayedTask(function() {
if (this.getActiveIndex() == this.items.length - 1) {
this.setActiveItem(0, 'slide');
}
else {
this.next();
}
this.pageTurner.delay(6000);
}, carousel);
carousel.pageTurner.delay(6000);
}
},
items: [
{
html : '<img src="resources/images/Picture1.png" width="100%" height = "100%" align="middle" /> <audio autoplay loop><source src="resources/audio/kalimba.mp3"></audio>',
style: 'backgroundImage: url(resources/images/bg.png);backgroundRepeat: repeat;backgroundPosition: center'
},
{
html : '<img src="resources/images/Picture2.png" width="100%" height = "100%" margin=0 align="middle" /> ',
style: 'backgroundImage: url(resources/images/bg.png);backgroundRepeat: repeat;backgroundPosition: center'
},
{
html : '<img src="resources/images/Picture3.png" width="100%" height = "100%" margin=0 align="middle" />',
style: 'backgroundImage: url(resources/images/bg.png);backgroundRepeat: repeat;backgroundPosition: center'
},
{
html : '<img src="resources/images/Picture3.png" width="100%" height = "100%" margin=0 align="middle" />',
style: 'backgroundImage: url(resources/images/bg.png);backgroundRepeat: repeat;backgroundPosition: center'
}
]
});
i write this code to auto side but its not working please help me..
There are quite many errors in your code. Please try this, as I've tested, it works (changes are only made to listeners):
listeners:
{
'show': function(carousel) {
carousel.pageTurner = new Ext.util.DelayedTask(function() {
if (carousel.getActiveIndex() == carousel.items.length - 2) {
carousel.setActiveItem(0, 'slide');
}
else {
carousel.next();
}
}, carousel);
carousel.pageTurner.delay(1000);
},
'activeitemchange': function(carousel){
if (carousel.getActiveIndex() == 0) {
carousel.fireEvent('show',this);
} else
carousel.pageTurner.delay(1000);
},
},
Some explanation:
afterrender event is replaced by paint event in Sencha Touch 2. In this situation, you can also use show event.
to set delay time after each cardswitch, you need to listen to activeitemchange event
Hope it helps.
I know there already an accepted answer, but here is my implementation of this (for sencha touch v2.2)
Tapping or manually sliding the image will pause the slideshow. Tapping again will resume.
Make sure you apply this to xtype: 'carousel'
{
xtype: 'carousel',
//...your config stuff here...
carouselSlideDelay: 3500,
autoSlide: true,
listeners: {
initialize: function(carousel) {
if (this.autoSlide) {
carousel.isRunning = false;
this.start(carousel);
// Add tap event.
carousel.element.on('tap', function(e, el){
if (!carousel.isRunning) {
carousel.next();
this.start(carousel);
} else {
this.stop(carousel);
}
}, this);
// Add drag event.
carousel.element.on('dragstart', function(e, el){
this.stop(carousel);
}, this);
}
}
},
start: function(carousel, delay) {
// If already running.
if (carousel.isRunning) { return; }
// Allow for overriding the default delay value.
var delay = (delay !== undefined ? delay : this.carouselSlideDelay);
carousel.isRunning = true;
carousel.timerId = setInterval(function () {
carousel.next();
if (carousel.getActiveIndex() === carousel.getMaxItemIndex()) {
carousel.setActiveItem(0);
}
}, delay);
},
stop: function(carousel) {
clearInterval(carousel.timerId);
carousel.isRunning = false;
}
}
And this was loosely based off the Sencha Touch demo here.
After chrome 43 bug. Auto carousel is not working in my app. so i did some customization
direction: 'horizontal',
delay: 10000,
start: true,
indicator:false,
listeners:
{
activate: function(homeScreenCarousel) {
var me=this;
homeScreenCarousel.pageTurner = new Ext.util.DelayedTask(function() {
if (me.getActiveIndex() == me.items.length-1) {
me.setActiveItem(0,'slide');
}
else {
me.setActiveItem(me.getActiveIndex()+1,'slide');
}
me.pageTurner.delay(8000);
}, homeScreenCarousel);
homeScreenCarousel.pageTurner.delay(8000);
},
activeitemchange:function(homeScreenCarousel){
var me=this;
homeScreenCarousel.pageTurner = new Ext.util.DelayedTask(function() {
if (me.getActiveIndex() == me.items.length - 1) {
me.setActiveItem(0, 'slide');
}
else {
me.setActiveItem(me.getActiveIndex()+1,'slide');
}
homeScreenCarousel.pageTurner.delay(8000);
}, homeScreenCarousel);
}
},

Categories

Resources