How to detect if context window of iframe has a video on the page?
window.onload = function () {
var pages = '#ViewBag.pages';
var p = JSON.parse(pages.replace(/("\;)/g, "\""));
var i = 0;
var mi = p.length - 1;
var interval;
console.log("frame is loaded");
var video = $(document).find("iframe").contents().find("video");
if (video.length == 1) {
console.log(0);
clearInterval(interval);
video.on('ended', function () {
document.getElementById('slider').src = src;
});
}
else { console.log(5);
interval = setInterval(function () {
i++;
if (i > mi) { i = 0 }
var src = p[i];
$.ajax({
async: false,
url: src,
type: 'GET',
success: function () {
document.getElementById('slider').src = src;
}
});
}, 5000);
}
}
Can anyone tell me what's wrong and why the page with video loops again and again without 'onended' event?
If you are using HTML5.
Here is an example -
$(document).ready(function(){
var videos = $(document).find("iframe").contents().find("video");
$(videos).each(function(){
$(this).on('ended', function(){
console.log('Video has ended!');
// Execute you function to move next slides
});
});
});
Related
when someone would immediatly scroll to the bottom after loading the code it would sometimes not update the id on time and load the same query
heres my script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
window.onscroll = function() {
if ((window.innerHeight + Math.ceil(window.pageYOffset)) >= document.body.offsetHeight) {
var lastId = $(".postid:last").attr("id");
var elem = document.getElementById("ele");
setTimeout(() => {
getMoreData(lastId);
elem.scrollIntoView();
}, 0);
}
}
function getMoreData(lastId) {
$(window).off("scroll");
$.ajax({
url: 'load_more.php?lastId=' + lastId,
type: "get",
beforeSend: function ()
{
$('.ajax-loader').show();
},
success: function (data) {
setTimeout(function() {
$('.ajax-loader').hide();
$("#post-list").append(data);
},1000);
}
});
}
</script>
What you probably want is to throttle the ajax requests after scroll event (say no more than once per 250ms).
You may use this function:
function throttle(func, timeFrame) {
var lastTime = 0;
return function() {
var now = Date.now();
if (now - lastTime >= timeFrame) {
func();
lastTime = now;
}
};
}
var count = 1;
var throttled = throttle(function() {
console.log("doing ajax " + count++);
}, 250)
window.addEventListener('scroll', throttled)
<body style="height: 4000px">
keep scrolling no matter what
</body>
In my code I am retrieved data from the data base every 30 seconds using AJAX. I want to use JavaScript to increment variable wht every time data is received from the database (every 30 seconds) and when if statement is true. Below code is working and incrementing to 1 but it doesn't go above 1. Does anyone has a solution for this problem?
<script>
$(document).ready(function () {
ajax_call = function() {
$.ajax({
type: "GET",
url: "test.php",
dataType: "html",
success: function (response) {
color = response;
console.log(color);
if (color == white){
var wht = (function(w) {
return function() {
w += 1;
return w;
}
}(0));
document.getElementById("memo").value = wht();
}else{
console.log("Color is not white");
}
var interval = 30000;
setInterval(ajax_call, interval);
});
</script>
<script>
const minusButtonFw = document.getElementById('memo-minus');
const plusButtonFw = document.getElementById('memo-plus');
var memo = document.getElementById('memo');
minusButtonFw.addEventListener('click', event => {
event.preventDefault();
const currentValue = Number(memo.value);
memo.value = currentValue - 1;
});
plusButtonFw.addEventListener('click', event => {
event.preventDefault();
const currentValue = Number(memo.value);
memo.value = currentValue + 1;
});
</script>
First of all your variable wht is a function. If you simply want to keep track of the number of time the if conditions is true you can do it by making the variable static (literaly). you can achive this by storing the variable in a global scope.
Also there are sytax errors in your code too where wht is defined.
try this
$(function () {
var memo = document.getElementById("memo");
memo.val = 0;
var ajax_call = function () {
$.ajax({
type: "GET",
url: "test.php",
dataType: "html",
success: function (response) {
color = response;
console.log(color);
if (color == white) {
memo.val++;
memo.value = memo.val;
} else {
console.log("Color is not white");
}
}
});
}
var interval = 30000;
setInterval(ajax_call, interval);
});
A Note:
If the response is managed by you, I would recomend sending the response as json rather than simply sending it as an html with just one value color.
You'll need to keep track of "w". Your current setup is using "w" as a parameter to a function. You'd need to keep it outside of the function and increment it from inside the function. You'll also need to wrap that function in an interval Something like the following:
var w = 0;
function setWhite(color) {
if (color == white) {
w++;
document.getElementById("memo").value = w;
} else {
console.log("Color is not white");
}
}
setInterval(function() {
setWhite(color);
}, 30000);
This should give you what you want. I didn't run the code so there are probably syntactical errors that you'll need to correct.
Try change the line
document.getElementById("memo").value = wht();
to
document.getElementById("memo").value = wht(document.getElementById("memo").value);
Your full code:
<script>
$(document).ready(function () {
ajax_call = function() {
$.ajax({
type: "GET",
url: "test.php",
dataType: "html",
success: function (response) {
color = response;
console.log(color);
if (color == white){
var wht = (function(w) {
return function() {
w += 1;
return w;
}
}(0));
document.getElementById("memo").value = wht(document.getElementById("memo").value);
}else{
console.log("Color is not white");
}
var interval = 30000;
setInterval(ajax_call, interval);
});
</script>
I made an example with setInterval. I made w global so it will work. Try this:
var w = 0;
var interval = setInterval(function() {
if (color == white) {
w++;
document.getElementById("memo").value = w;
} else {
console.log("Color is not white");
}
}, 30000);
i am trying to make a slider, i have function that getting array of objects and loop it, and i have select that change models list, but when i change select, old instance of function still work, they are starting to work together. So i add function stopper, but it wont work. Help please, thank you!
var keepGoing = true;
function slideList(models) {
$.each(models, function (index, model) {
setTimeout(function () {
if (keepGoing != false) {
moditem.innerHTML = "";
modlist.value = model.id;
var photo = document.createElement('IMG');
photo.src = model.photos[0].file;
photo.classList.add('img');
moditem.appendChild(photo);
if (index >= models.length - 1) {
slideList(models);
}
} else {
return false;
}
},
5000 * index);
});
}
function startLoop() {
keepGoing = true;
}
function stopLoop() {
keepGoing = false;
}
$("#car-type-select").on('change', function () {
stopLoop();
getModels(this.value);
});
Clear timeout:
var timer;
function slideList(models) {
$.each(models, function (index, model) {
timer = setTimeout(function () {
moditem.innerHTML = "";
modlist.value = model.id;
var photo = document.createElement('IMG');
photo.src = model.photos[0].file;
photo.classList.add('img');
moditem.appendChild(photo);
if (index >= models.length - 1) {
slideList(models);
}
},
5000 * index);
});
}
$("#car-type-select").on('change', function () {
clearTimeout(timer);
getModels(this.value);
});
Other unimportant functions
function getModels(cartype_id) {
$.ajax({
type: 'POST',
url: '/home/models/get',
data: {
'cartype_id': cartype_id
},
success: function (models) {
makeList(models);
slideList(models)
}
});
}
function makeList(models) {
modlist.innerHTML = "";
$.each(models, function (index, model) {
var option = document.createElement("option");
option.text = model.manufacturer.name + ' ' + model.name;
option.value = model.id;
modlist.add(option);
});
}
You need to use clearTimeout to stop function in setTimout to stop executing.
Example:
var timer = setTimeout(function(){ /* code here */ }, 3000)
clearTimeout(timer) //it will stop setTimeout function from executing.
After looking at code update:
Can you please try:
var timers = [];
function slideList(models) {
$.each(models, function(index, model) {
timers.push(setTimeout(function() {
moditem.innerHTML = "";
modlist.value = model.id;
var photo = document.createElement('IMG');
photo.src = model.photos[0].file;
photo.classList.add('img');
moditem.appendChild(photo);
if (index >= models.length - 1) {
slideList(models);
}
},
5000 * index));
});
}
$("#car-type-select").on('change', function() {
$.each(timers, function(i, timer) {
clearTimeout(timer);
})
getModels(this.value);
});
setTimeout is getting called in loop to need array of setTimeout references
I have this code:
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0;
var timer = setInterval(function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
}, 3000);
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
clearInterval(timer);
}
});
$el.mouseout({
timer;
});
});
I want to suspend the function on mouseover and resume it on mouse out but I cant get the latter right. How can I resume it?
Thank you.
There are two ways:
Set a flag that the function being called by the interval checks, and have the function not do anything if it's "suspended."
Start the interval again via a new setInterval call. Note that the old timer value cannot be used for this, you need to pass in the code again.
Example of #1:
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0,
suspend = false; // The flag
var timer = setInterval(function() {
if (!suspend) { // Check it
$el.removeClass("current").eq(++c % tot).addClass("current");
}
}, 3000);
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
suspend = true; // Set it
},
mouseleave: function(e) {
suspend = false; // Clear it
}
});
});
Example of #2:
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0,
timer = 0;
// Move this to a reusable function
var intervalHandler = function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
};
// Probably best to encapsulate the logic for starting it rather
// than repeating that logic
var startInterval = function() {
timer = setInterval(intervalHandler, 3000);
};
// Initial timer
startInterval();
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
clearInterval(timer); // Stop it
}
mouseleave: function(e) {
startInterval(); // Start it
}
});
});
Checkout these prototypes:
//Initializable
function Initializable(params) {
this.initialize = function(key, def, private) {
if (def !== undefined) {
(!!private ? params : this)[key] = (params[key] !== undefined) ? params[key] : def;
}
};
}
function PeriodicJobHandler(params) {
Initializable.call(this, params);
this.initialize("timeout", 1000, true);
var getTimeout = function() {
return params.timeout;
};
var jobs = [];
function Job(params) {
//expects params.job() function
Initializable.call(this, params);
this.initialize("timeout", getTimeout(), true);
this.initialize("instant", false);
var intervalID = undefined;
this.start = function() {
if (intervalID !== undefined) {
return;
}
if (this.instant) {
params.job(true);
}
intervalID = setInterval(function() {
params.job(false);
}, params.timeout);
};
this.stop = function() {
clearInterval(intervalID);
intervalID = undefined;
};
}
this.addJob = function(params) {
jobs.push(new Job(params));
return jobs.length - 1;
};
this.removeJob = function(index) {
jobs[index].stop();
jobs.splice(index, 1);
};
this.startJob = function(index) {
jobs[index].start();
};
this.stopJob = function(index) {
jobs[index].stop();
};
}
Initializable simplifies member initialization, while PeriodicJobHandler is able to manage jobs in a periodic fashion. Now, let's use it practically:
var pjh = new PeriodicJobHandler({});
//It will run once/second. If you want to change the interval time, just define the timeout property in the object passed to addJob
var jobIndex = pjh.addJob({
instant: true,
job: function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
}
});
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0;
var timer = setInterval(function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
}, 3000);
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
jobIndex.stop();
}
});
$el.mouseout({
jobIndex.start();
});
});
With Javascript, it is much easy and efficient.
You can change the interval in setInterval function.
It is checking whether suspend variable is false or true, here suspend variable is setting to true, if mouseEnter function is called and set to false if mouseLeave function is called.
var displayMsg = document.getElementById('msg').innerHTML;
var i = 0;
var suspend = false;
var sequence = setInterval(update, 100);
function update() {
if (suspend == false) {
var dispalyedMsg = '';
dispalyedMsg = displayMsg.substring(i, displayMsg.length);
dispalyedMsg += ' ';
dispalyedMsg += displayMsg.substring(0, i);
document.getElementById('msg').innerHTML = dispalyedMsg;
i++;
if (i > displayMsg.length) {
i = 0;
}
}
}
document.getElementById('msg').addEventListener('mouseenter', mouseEnter);
document.getElementById('msg').addEventListener('mouseleave', mouseLeave);
function mouseEnter() {
suspend = true;
}
function mouseLeave() {
suspend = false;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#msg {
width: 680px;
height: 100px;
border: 1px solid #ccc;
padding-left: 15px;
}
</style>
</head>
<body>
<div id="msg">
Today is only 15% discount. Hurry up to grab. Sale will end sooooooooooooon!!!!
</div>
<div id="output"></div>
<script src="marquee.js"></script>
</body>
</html>
Here in the below code iam calling ajax on scroll.
But this is calling ajax multiple times. To restrict this i added setTimeout function and flag (i.e. isActive) still it is calling two times.
Please help me where iam going wrong.
Thanks in advance
var isActive = false;
var sIndex =12;
var myflag = '1';
var offSet = 12;
var timeout;
jQuery(window).scroll(function () {
if(typeof timeout == "number") {
window.clearTimeout(timeout);
delete timeout;
}
timeout = window.setTimeout( check, 500);
});
function check(){
var cat = $(".mi-selected").attr('id');
var tecID = $("#technologyID").val();
var notSameInd = $("#notSameInd").val();
var sIndex =$("#startInd").val();
if (!isActive && ($(window).scrollTop() + $(window).height() == $(document).height()) && (sIndex !== notSameInd) ) {
var isActive = true;
jQuery.ajax({
type: "POST",
url: 'http://some.com/responcePortfolio.php',
data: {
tecID:tecID,
cat:cat,
startIndex:sIndex,
offset:offSet,
count_now:count_now
},
success: function (result) {
if(result !== ''){
jQuery("#LoaderImage").hide();
jQuery("#portfolioList").append(result);
$("#notSameInd").val(sIndex);
sIndex = parseInt(sIndex) + parseInt(offSet);
$("#startInd").val(sIndex);
}
else{
jQuery("#LoaderImage").hide();
}
isActive = false;
},
error: function (error) {
//alert(error);
}
});
}
}