jquery play sound on body replacement - javascript

I have a simple site which gets refreshed once every 30 seconds via a jquery full body refresh.
Now once a page refresh occurs I want a short sound to play and I tried to do this with various methods.
the methods work on my pc (IE, chrome and firefox) but the target is a samsung smart tv.
this is my site refresh with the sound added:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function update_site() {
$.ajax({
url: "test.html",
dataType: "html",
cache: false,
success: function(data) {
// Replace body with loaded site. You can do more checks here to check
// if the fetched content is all there.
var body_html = data.replace(/^[\S\s]*<body[^>]*?>/i, "")
.replace(/<\/body[\S\s]*$/i, "");
$('body').html(body_html);
$('.last_connect').css('background-color', 'blue');
$("#goldengun").get(0).play();
},
error: function(data) {
$('.last_connect').css('background-color', 'red');
}
});
}
// Run every 20 secs.
window.setInterval(function() {
update_site();
}, 20000);
</script>
<style>
.last_connect {
background-color: green;
position: fixed;
top: 0px;
right: 0px;
height: 4%;
width: 2%
}
</style>
</head>
<body>
<div class="last_connect">
</div>
<audio id='goldengun'>
<source src="test.mp3" type="audio/mpeg">
</audio>
<button type="button" onclick="update_site();">update site!</button>
</body>
</html>
like I said this works in my browsers but not on the smart tv, the window refreshes successfully but the sound does not get played. However if I make a single function which ONLY plays the audio and call that on my setinterval it works. If call that function from my update_site() function it doesn`t work. it seems to me this some kind of syncing issue where the browser has not yet loaded everything and it already request to play the sound.
Does anyone have an idea on how to fix this?
help would be greatly appreciated.

use Buzz ( http://buzz.jaysalvat.com/ ). I love it. It uses html5 audio and can play ogg, mp3, and wav as long as the browser supports in in js without creating an audio element.
Example:
function playSound(){
var mySound = new buzz.sound( "/sounds/sound", {
formats: [ "ogg", "mp3", "aac" ]
});
mySound.play();
}
or even simpler:
var sound = new buzz.sound('assets/audio/sound.mp3');
and then where you call the function, call sound.play();
Unless and maybe even if you are dynamically creating sound files, you should know the names. So load the body with jQuery's .load() like so:
$('body').load('newPage.html body');
now you can know when the load is complete instead of a refresh which one can't listen for.
So do:
var sound = new buzz.sound("/sounds/sound.mp3");
$('body').load('newPage.html body', function(){
sound.play();
});
So what this does is it defines the sound, then loads newPage.html's body into the current page's body and when that is done, it plays the sound.
I recommend having the new sound associated with the new page's name or store in a variable.
Suppose I need to load new page and play sound ' abc.mp3 ' on click of an element, I can do:
var sound = new buzz.sound('/sounds/sound.mp3');
$('.element').click(function(){
var pageToLoad = 'abc';
$('body').load(pageToLoad+'.html body', function(){
sound = new buzz.sound('sounds/'+pageToLoad+'.mp3');
sound.play();
});
});
What this does it defines the sound. Then on an event, in this case on click of anything with the class="element", it loads the body of page abc.html and then plays abc.mp3 once that loading is finished.

Unable to test, but perhaps something like this would work?
The following script in the test.html page:
<script type="text/javascript">
var aud = $('<audio>').attr('id', 'goldengun');
var src = $('<source>').attr('src', 'test.mp3').attr('type', 'audio/mpeg');
aud.append(src);
</script>
The following function in caller page:
function update_site() {
$.ajax({
url: "test.html",
dataType: "html",
cache: false,
success: function(data) {
// Replace body with loaded site. You can do more checks here to check
// if the fetched content is all there.
var body_html = data.replace(/^[\S\s]*<body[^>]*?>/i, "")
.replace(/<\/body[\S\s]*$/i, "");
$('body').html(body_html);
$('.last_connect').css('background-color', 'blue');
$('body').append(aud);
aud.get(0).play();
},
error: function(data) {
$('.last_connect').css('background-color', 'red');
}
});
}
window.setInterval(function() {
update_site();
}, 1000);
Or just try:
function update_site() {
$.ajax({
url: "test.html",
dataType: "html",
cache: false,
success: function(data) {
// Replace body with loaded site. You can do more checks here to check
// if the fetched content is all there.
var body_html = data.replace(/^[\S\s]*<body[^>]*?>/i, "")
.replace(/<\/body[\S\s]*$/i, "");
$('body').html(body_html);
$('#goldengun', body_html).get(0).play();
$('.last_connect').css('background-color', 'blue');
},
error: function(data) {
$('.last_connect').css('background-color', 'red');
}
});
}
It's quite likely that the browser itself under Android is disallowing .play() calls in a timed loop.

Related

Error with jQuery load function in Chrome

I have this problem, when I load /index.php?route=quickcheckout/checkout with jQuery function load it's load perfectly in FF in IE and sometimes even in Chrome.
But sometimes in Chrome it doesn't load content from /index.php?route=quickcheckout/checkout but load the page you are on in div with id blagajna.
Here is my code for this:
<script type="text/javascript">
$(".img-thumbnail").click(function () {
$(this).prev('input:radio').prop('checked', true);
});
$('form').on('click', '.img-thumbnail', function() {
var url = "/index.php?route=checkout/cart/add";
$.ajax({
type: "POST",
url: url,
data: $("#oko").serialize(),
async: false,
success: function(data)
{
$('input:radio').prop('checked', false);
$(".izbira").hide();
$(".dodano").show().delay(1500).fadeOut();
$("#blagajna").load( "/index.php?route=quickcheckout/checkout" );
}
});
return false;
});
</script>
and this is URL: http://trgagate.si/index.php?route=product/product&product_id=50#narocilo
Problem appears only in Chrome when you click on some bottle in order form.
Thanks for help.
The error appears to be generated in a file that is returning some script
<script type="text/javascript"><!--
$('.colorbox').colorbox({
width: 640,
height: 480
});
//--></script>
colorbox is calling the live() function which may be deprecated. If you have access to the jquery.colorbox-min.js file just do a find+replace and change all references of "live" to "on"

Load video source into videojs or mediaelementjs dynamically from ajax?

I need to load video source, multiple types, from another website, which on get returns text link into video.
For example i open:
http://www.getthisvideoexample.com?whichvideo=id0
it shows in web browser text link:
http://someotherserver.com/somesubdomainrandomuniquenumber/thisisyourvideovalidforsometime.mp4
or
http://www.getthisvideoexample.com?whichvideo=id0&webm=true
and it shows in web browser text link:
http://someotherserver.com/somesubdomainrandomuniquenumber/thisisyourvideovalidforsometime.webm
But this server sometimes, when load is high,returns 500 error.
So i need to handle it all.
Lets take for example:
<video id="myVideo"></video>
var player = new MediaElementPlayer('#myVideo', {
type: ['video/mp4', 'video/webm'],
success: function (mediaElement, domObject) {
var sources = [
{ src: "HOW_TO_PUT_HERE_DYNAMICALLY_LOADED_MP4_LINK?", type: 'video/mp4' },
{ src: "HOW_TO_PUT_HERE_DYNAMICALLY_LOADED_WEBM_LINK?", type: 'video/webm' }
];
mediaElement.setSrc(sources);
mediaElement.load();
mediaElement.play();
}
});
Also how to make it so, that if 500 or other error is returned instead of link to video, code will just wait few seconds and try again, or display message with text "trying again, wait...."?
Thanks.
I would try a different approach.
I would place an ajax request (using jQuery.ajax()) within a setInterval loop (every 2 seconds perhaps). If the AJAX request, either
http://www.getthisvideoexample.com?whichvideo=id0 // returns a MP4 file
... or
http://www.getthisvideoexample.com?whichvideo=id0&webm=true // returns a webm file
... is successful, then clear the interval (clearInterval()), otherwise keep trying until the server responds successfully (you may need to set a method to clear the interval after some time in case the server is not available, otherwise you will end up in an infinity loop)
How-to?
If the ajax request is successful, then I would build the <video> tag structure with the response and append the tag to a video container (a <div> perhaps)
Then I would bind MEJS to the selector of the newly appended tag like :
var URL = "http://www.getthisvideoexample.com?whichvideo=id0 "; // request video URL
jQuery(document).ready(function ($) {
var getVideo = setInterval(function () {
$.ajax({
url: URL,
cache: false,
dataType: "json", // or else
success: function (response) {
clearInterval(getVideo); // ends loop
// build video tag
// select proper type, based on response
var video = '<video id="video_player" width="320" height="240" controls>' +
'<source src="' + response + '" type="video/' + (response.indexOf("webm") == -1 ? 'mp4' : 'webm') + '" />' +
'</video>';
// target container's selector
$("#videoContainer")
.html(video) // insert video tag
.find("#video_player") // find video selector after insertion
// bind MEJS
.mediaelementplayer({
// MEJS options
});
},
error: function () {
// error in ajax, will try again in 2 seconds
}
});
}, 2000);
}); // ready

Build HTML5 video content, then play video on click event iOS

I have a content area that gets dynamically loaded with new content when you press the previous or continue buttons. A simple example of html is:
<div id="contentArea"></div>
<nav>
<ul>
<li class="butPrev">Previous</li>
<li class="butNext">Next</li>
</ul>
</nav>
What I used to do in iOS6 is have a mask over the content area on first load that I could click to trigger audio and video and then all other dynamic HTML5 videos would play. I am not sure about iOS7, but iOS8 doesn't allow this. I would have to do it for each page, which defeats the purpose of the mask and is a pain for a user.
As an alternative, I am trying to trigger the play of videos with the next button click. The problem is that the next button captures the dynamic content, loads it into the content area and at that time needs to trigger the play, which iOS doesn't like. Is there any way to wait until the content area is loaded, while staying within the click event so it doesn't get blocked? Here is what I am trying (I have stripped out the Ajax stuff):
var contentLoaded = false;
$('nav li').click(function(){
contentLoaded = false;
//load HTML with HTML5 video via Ajax
//when done, sets contentLoaded = true
triggerAutoplay();
});
function triggerAutoplay() {
if (contentLoaded) {
$('video[autoplay]').each(function(){
if ($('this').attr('autoplay') != "false") {
this.play();
}
});
} else {
setTimeout(triggerAutoplay,100);
}
}
im not sure if i understand you right, but maybe you should call the play in the success of your ajax call like so:
$('nav li').click(function(){
$.ajax({
url: "whatever"
}).done(function() {
//do some stuff
triggerAutoplay();
});
});
function triggerAutoplay() {
$('video[autoplay]').each(function(){
if ($('this').attr('autoplay') != "false") {
this.play();
}
});
}
The play trigger has to be within the click function, so I have to set async to false so that the ajax completes before the function is call like:
$('nav li').click(function(){
$.ajax({
url: "whatever",
async: false
});
triggerAutoplay();
});
function triggerAutoplay() {
$('video[autoplay]').each(function(){
if ($('this').attr('autoplay') != "false") {
this.play();
}
});
}

Loading JavaScript into AJAX loaded content

I am a newbie with AJAX and JavaScript and not sure how to make it work.
Here is the website:
When portfolio images are clicked, the details are loaded via AJAX. I would like to be able to do a slideshow for the work that has more than one full-sized image. However, because the content is loaded using AJAX, Flexslider's JavaScript doesn't work.
Here is the code that loads the content:
// ----------- PROJECT WINDOW SHOW/HIDE ----------- //
var $actual= null;
$(".ch-grid").click(function() {
$.scrollTo( $('#project-show'), 800, {offset:-130});
obre($(this).attr('id'));
$actual=$(this);
// alert($('.project-content').position().top)
// $('html, body').animate({scrollTop:($('.project-content').position().top)+165}, 1000);
});
$(".portfolio-btn").click(function() {
obert=false;
});
function obre(quin){
$.ajax({
//type: "POST",
//data: { id: $(this).attr('cid')},
url: quin,
success: function(data) {
$('.project-content').html(data);
}
});
}
And here are the scripts that need to be loaded:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js?ver=1.9.1"></script>
<script type="text/javascript" src="http://www.4ndesign.com/wp-content/themes/4ndesign/js/metronomy-plugins.js?ver=2.0"></script>
<script type="text/javascript" src="http://www.4ndesign.com/wp-content/themes/4ndesign/js/metronomy-custom.js?ver=2.2"></script>
You need to do your init of flexslider after the content is loaded via ajax.
Just add it into the success part of your ajax request.
$.ajax({
..
success: function(data) {
$('#slider').flexslider(); // or what ever :)
}
});

optimizing colorbox and adding extra jquery

I have two problems
I am trying to open a jQuery colorbox and it is very slow. The reason is I am trying to get html content from a different page (I cannot use iframe because I just need a part of this page). The following code works but it takes time after the button is clicked:
$(document).ready(function() {
$(".cart-link a").click(function(event) {
$(this).colorbox.close();
});
$(".rest-menuitem a").click(function(event) {
event.preventDefault();
var result = null;
var sURL = $(this).attr("href");
$.colorbox({
html: function() {
$.ajax({
url: sURL,
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
}
});
return $(result).find('.product');
},
width: '650px',
height: '10px',
onComplete: function() {
$(this).colorbox.resize();
}
});
});
});
I want to know if there is a alternative way to do it. I dont mind if the colorbox popup and then takes time to load the content. The above version can be fount at this url (http://delivery3.water-7.com/index.php/restaurants/manufacturers/3/Barcelona-Restaurant-&-Winebar/products).
I am also trying to close the colorbox when a user clicks on add to cart. But some reason it is not triggered. $(".cart-link a").click is not triggered when I click on add to cart. Is there a special way to add jquery to colorbox content?
Try this instead:
$(".rest-menuitem a").colorbox({
href: function(){
return $(this).attr('href') + ' .products';
},
width: '650px',
height: '10px',
onComplete: function() {
$(this).colorbox.resize();
}
});
ColorBox uses jQuery's load() method for it's ajax handling, so you just need to add the desired selector to the link's href.
For your question 2 can you try this ?
$(document).ready(function() {
$(".cart-link a").live('click',function(event) {
$(this).colorbox.close();
});
});
For your question 1..it will be slow since you are fetching it from different page.Use a different logic for that
For your question no 1
$('selector').colorbox({onLoad: function() { /*Intially load a empty color box with only <div id="contenttoload"></div> (No other html content */
$.ajax({
url :'Your url',
data : {}, //data to send if any
type : "POST" //or get
success:function(data){ /*data means the stuff you want to show in color box which you must return from the other page*/
$('#contenttoload').html(data); //data should be well formatted i mean add your css,classes etc from the server itself */
}
});
}});

Categories

Resources