I was successful in getting the id of all images within a div when clicking the div with the following codes below:
<script type="text/javascript">
function getimgid(){
var elems = [].slice.call( document.getElementById("card") );
elems.forEach( function( elem ){
elem.onclick = function(){
var arr = [], imgs = [].slice.call( elem.getElementsByTagName("img") );
if(imgs.length){
imgs.forEach( function( img ){
var attrID = img.id;
arr.push(attrID);
alert(arr);
});
} else {
alert("No images found.");
}
};
});
}
</script>
The codes above works perfectly, doing an alert message of the image id when clicking card div. Now what I want is to run this function without clicking the div in every 5 seconds. I have tried setInterval (getimgid, 5000), but it doesn't work. Which part of the codes above should I modify to call the function without clicking the div. Any help would be much appreciated.
JSFiddle
You should be calling it this way:
setInterval (function(){
getimgid();
},5000);
also remove binding of click event for element.
Working Fiddle
Use elem.click() to trigger click
function getimgid() {
var elems = [].slice.call(document.getElementsByClassName("card"));
elems.forEach(function (elem) {
elem.onclick = function () {
var arr = [],
imgs = [].slice.call(elem.getElementsByTagName("img"));
if (imgs.length) {
imgs.forEach(function (img) {
var attrID = img.id;
arr.push(attrID);
alert(arr);
});
} else {
alert("No images found.");
}
};
elem.click();
});
}
setInterval(getimgid, 1000);
DEMO
Problem: You are not triggering the click in setInterval. You are only re-running the event binding every 5 secs.
Solution: Set Interval on another function which triggers the click. Or remove the click binding altogether if you don't want to manually click at all.
Updated fiddle: http://jsfiddle.net/abhitalks/3Dx4w/5/
JS:
var t;
function trigger() {
var elems = [].slice.call(document.getElementsByClassName("card"));
elems.forEach(function (elem) {
elem.onclick();
});
}
t = setInterval(trigger, 5000);
Related
I am trying to call a function after the image loads completely in DOM.
The image structure is created dynamically on AJAX call success and the image url is also added in success using the result of API call.
Problem:
I want to call a function after the image loads completely in DOM.
To do this I have used JQuery load event.
Function which is called on load.
function carouselHeight() {
$('.home-banner-img-container').each(function() {
var $this = $(this);
var dynamicheight = $(this).parent();
var sectionInnerHeight = $this.innerHeight();
dynamicheight.css({
'height': sectionInnerHeight
});
});
}
I have tried below steps but it didn't worked
$(window).on('load', function() {
carouselHeight();
});
$(window).on('load', 'img.image-preview', function() {
carouselHeight();
});
$(document).on('load', 'img.image-preview', function() {
carouselHeight();
});
The first method $(window).on('load', function() {}) works perfectly on hard reload but on normal reload it is not able to find $('.home-banner-img-container') element which is inside of carouselHeight function.
Please help me to find a solution for this. Thank you.
I have found the solution on stack overflow where I have added the below code in ajax call complete method.
function imageLoaded() {
// function to invoke for loaded image
// decrement the counter
counter--;
if( counter === 0 ) {
// counter is 0 which means the last
// one loaded, so do something else
}
}
var images = $('img');
var counter = images.length; // initialize the counter
images.each(function() {
if( this.complete ) {
imageLoaded.call( this );
} else {
$(this).one('load', imageLoaded);
}
});
I have multiple divs in one html page under common wrapper class.
I am using hide and show method on clicking next and previous option.
What I am trying to achieve: On page reload/refresh, the div which is showing currently should show after page reload.
So in short if you reload/refresh from pink screen, it should show same pink screen after page reload.
What I tried: I am storing the display properties (none or block) is local storage and on page reload trying to give same properties to divs again. Most of the responses and solution I checked in Stack overflow is regarding opening the same tab when refresh. but my case is what in same tab I have multiple div and I want to open from the same state which it was earlier.
Logic I used:
$(window).on('load', function(){
var disp = localStorage.getItem("disp");
var ustatus = JSON.parse(disp);
$(".chk").text(ustatus);
for (var x=ustatus; x<ustatus.length; x++){
$(".pg"+x).css("display", ustatus[x]);
}
});
This is fiddle link I tried:
Page reload demo JS Fiddle link
Your HTML and CSS code is perfect but you need to make corrections in your JavaScript code.
Observation 1 : You "for" loop to assign display style has problem with variable x. You need to assign integer value to x.
Observation 2 : You need to remove that "display" style from "div" elements when you click on "next" and "previous" links.
Hear is new Js fiddle link with updated code.
$(window).on('load', function () {
//localStorage.removeItem("disp");
var disp = localStorage.getItem("disp");
var ustatus = JSON.parse(disp);
$(".chk").text(ustatus);
for (var x = 1; x <= ustatus.length; x++) {
$(".pg" + x).css("display", ustatus[x-1]);
}
});
$(".next").on("click", function () {
$(this).parent().addClass("off").removeClass("on").removeAttr("style");
$(this).parent().next().addClass("on").removeClass("off").removeAttr("style");
});
$(".prev").on("click", function () {
$(this).parent().addClass("off").removeClass("on").removeAttr("style");
$(this).parent().prev().addClass("on").removeClass("off").removeAttr("style");
});
$(window).on('beforeunload', function () {
var display = $(".clr").map(function () {
return $(this).css("display");
}).get();
localStorage.setItem("disp", JSON.stringify(display));
});
You can also download this file. Please run index.html to see the output.
You don't really need the on class:
$(window).on('load', function(){
var disp = localStorage.getItem("disp");
var ustatus = JSON.parse(disp);
$(".chk").text(ustatus);
for (var x=0; x<ustatus.length; x++){
$(".pg"+(x+1)).toggleClass("off", ustatus[x]);
}
});
$(".next").on("click", function(){
$(this).parent().addClass("off");
$(this).parent().next().removeClass("off");
});
$(".prev").on("click", function(){
$(this).parent().addClass("off");
$(this).parent().prev().removeClass("off");
});
$(window).on('beforeunload', function(){
var display = $(".clr").map(function(){
return $(this).hasClass("off");
}).get();
localStorage.setItem("disp", JSON.stringify(display));
});
Fiddle
note: you can't use $(window).on('load', ...) in a fiddle - the JS in the editor is run on load
EDIT: you might also want to validate ustatus before applying it, something like
if (Array.isArray(ustatus) && ustatus.filter(x => x === true).length === 1) {
for (var x=0; x<ustatus.length; x++){
$(".pg"+(x+1)).toggleClass("off", ustatus[x]);
}
}
You can do it without using display, you can use on and off classes, i think that's why they are created for
$(window).on('load', function(){
var disp = localStorage.getItem("disp");
var ustatus = JSON.parse(disp);
if(ustatus!=undefined){
$(".chk").text(ustatus);
for (var x=1; x<=ustatus.length; x++){
if(ustatus[x-1]=='on'){
$(".pg"+x).addClass("on").removeClass("off");
}
else{
$(".pg"+x).addClass("off").removeClass("on");
}
}
}
$(".next").on("click", function(){
$(this).parent().addClass("off").removeClass("on");
$(this).parent().next().addClass("on").removeClass("off");
});
$(".prev").on("click", function(){
$(this).parent().addClass("off").removeClass("on");
$(this).parent().prev().addClass("on").removeClass("off");
});
$(window).on('beforeunload', function(){
var display = $(".clr").map(function(){
if($(this).hasClass('on'))
return 'on';
else
return 'off';
}).get();
localStorage.setItem("disp", JSON.stringify(display));
});
});
This is my script -
my script alert when someone touch on any place on the page .
I am trying to execute alert only one time and not on every click.
This is the code i built which alert any time .
$( document ).ready(function() {
var click_count = 0;
if (click_count == 0){
$('body').click(function(){
alert();
var click_count = 1;
});
}
});
You have your if in the wrong place. You want it inside the click handler (the code that runs when the click occurs), not outside it. You also need to remove the var from var click_count = 1; so you 're using the one declared in the ready callback, not the one declared in the click handler:
$(document).ready(function() {
var click_count = 0;
$('body').on("click", function() {
if (click_count == 0) {
alert("Hi there");
click_count = 1;
}
});
});
Testing 1 2 3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
(Here's a runnable version for mobiles where Stack Snippets aren't rendered: http://output.jsbin.com/taropelopu)
But, rather than using click_count, I'd suggest removing the event handler after the first click. You could do that with off, but jQuery even has a function specifically for adding a handler you remove the first time it's called: one (rather than on):
$(document).ready(function() {
$('body').one("click", function() {
alert("Hi there");
});
});
Testing 1 2 3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
(Runnable version for devices where Stack Snippets don't render: http://output.jsbin.com/wivoroluzu)
With plain JavaScript you can do
let clicked = false;
const clickOnce = () => {
if (!clicked) {
alert('clicked');
clicked = true;
}
};
document.body.addEventListener('click', clickOnce);
some body content
And you don't even need a clicked variable to store the state. Just remove the event listener once it is triggered.
const clickOnce = () => {
alert('clicked');
document.body.removeEventListener('click', clickOnce)
};
document.body.addEventListener('click', clickOnce);
some body content
I try to resize an iframe with jQuery and JS. First I get the iframe out of a list of iframes and resize it when the iframe-content is ready.
NOTE: The two-steps resize is necessary because otherwise after the
content of the iframe-page is a huge space.
Problem: In the while-loop I check if the content of the iframe is ready, when not I set a timeout of 1 second. But jQuery don’t check if the content ready it always goes inside the if and try to resize the iframe but fails because jQuery cannot get the size of a NULL element.
Has someone of you a solution for my problem?
My Code:
$(document).ready(function () {
var iframes = $(".my-iframe");
$.each(iframes, function () {
resizeIframe(this);
});
});
function resizeIframe(iframe) {
$(iframe).width("100%");
var iframeIsReady = false;
do
{
if ($(iframe).ready)
{
var iframeHeight = iframe.contentDocument.body.scrollHeight;
$(iframe).height(iframeHeight);
var iframeContentHeight = $(iframe).children("#DivInPage").height();
$(iframe).height(iframeContentHeight);
iframeIsReady = true;
}
else
{
setTimeout(resizeIframe(iframe), 1000);
}
}while(!iframeIsReady);
}
Edit:
Check out my solution
Hi there is small change in your code please check following.
$(document).ready(function () {
var iframes = $(".my-iframe")[0]; // $(".my-iframe"); /Edited
$.each(iframes, function () {
resizeIframe(this);
});
});
function resizeIframe(iframe) {
$(iframe).width("100%");
var iframeIsReady = false;
do
{
if ($(iframe.contentDocument).ready) // added 'iframe.contentDocument' instead of iframe
{
var iframeHeight = iframe.contentDocument.body.scrollHeight;
$(iframe).height(iframeHeight);
var iframeContentHeight = $(iframe).children("#DivInPage").height();
$(iframe).height(iframeContentHeight);
iframeIsReady = true;
}
else
{
setTimeout(resizeIframe(iframe), 1000);
}
}while(!iframeIsReady);
}
try this.
I checked code again found that $(".my-iframe") returns array of element object.
We need object here not array.
So i hard coded 0th index. you can use id instead of this.
Solution of my problem is:
$(document).ready(function () {
var iframes = $(".my-iframe");
$.each(iframes, function () {
resizeIframe(this);
});
});
function resizeIframe(iframe) {
$(iframe).width("100%");
setInterval(function () {
//Check if the Content inside the iframe is ready
if ($(iframe.contentDocument.body).ready) {
var iframeHeight = iframe.contentDocument.body.scrollHeight;
$(iframe).height(iframeHeight);
var iframeContentHeight = $(iframe).children("#DivInPage").height();
$(iframe).height(iframeContentHeight);
//Close the Function
return;
}
}, 1000);
}
The code of the first function shows three different divs on specific Interval 5seconds (div1,div2,div3).
The code of the second function used to stop showing the divs.
while showing div2 , I clicked the link to stop at that point it got stopped.But after that i clicked it again and it shows div1 (its getting toggling fine) but i would like to continue next action which was to show div3.
Jquery Code :
$(function() {
var IntervalId;
function first_function() {
var counter = 0,
divs = $('#div1,#div2,#div3');
function showDiv () {
divs.hide() // hide all divs
.filter(function (index) { return index == counter % 3; })
.show('fast'); // and show it
counter++;
};
showDiv();
IntervalId = setInterval(showDiv, 5000);
};
function second_function(){
clearInterval(IntervalId);
}
$("#link1").toggle(
first_function,second_function
);
});
Html Code :
Toggle
move the initialization of counter outside first_function():
$(function() {
var IntervalId;
var counter = 0,
function first_function() {
divs = $('#div1,#div2,#div3');
...
In your example, every time you call first_function(), the counter is set back to zero.
Have fun with:
<script type="text/javascript">
$(function() {
var divFunctions = [];
var $divs = $('#div1,#div2,#div3');
$divs.each(function() {
var $this = $(this);
divFunctions.push(function() {
return function() {
$divs.not($this).hide();
$this.show("fast")
};
}());
});
var $toggle_button = $("#link1");
$toggle_button.toggle.apply($toggle_button, divFunctions);
});
</script>
<body>
Toggle
<div id='div1' style="display:none;">content1</div>
<div id='div2' style="display:none;">content2</div>
<div id='div3' style="display:none;">content3</div>
</body>