How to scroll to an element using Javascript? - javascript

I'm trying to scroll to a particular card when a button is clicked. I'm using scrollIntoView for that, but its not working.
.js file :
document.getElementById("general_details_edit").addEventListener("click", function(){
this.style.display = "none";
document.getElementById("general_details_card").classList.remove("d-none");
document.getElementById("general_details_card").classList.add("d-block");
console.log("start");
document.getElementById("general_details_card").scrollIntoView({behavior : 'smooth'});
console.log("end")
//not working
All of the other javascript code is working. How can i resolve this?
I get the console messages "start" and "end" as well.
Also, when i run the same line from browser's console, it works.
EDIT :
Vijay's comment about using a timeout worked for me. But how i can wait for the element to load instead of waiting for a specific amount of time?
Current code :
const scroll = (el) => {
setTimeout(function () { el.scrollIntoView( {behavior : 'smooth', block : 'end'}); }, 500);
}

One way would be to change the waiting time to zero milliseconds once the DOM is fully loaded.
var mSeconds = 500;
window.addEventListener('DOMContentLoaded', function(event) {
mSeconds = 0;
});
const scroll = (el) => {
setTimeout(function () {
el.scrollIntoView( {behavior : 'smooth', block : 'end'});
}, mSeconds);
}

Related

do something when js element is loaded , is not working

I have this Jquery function to click on an element when its ready. its an interval doing it , the following function:
MonitorAndClick(selector) {
var ele = $(selector);
if (ele.length == 0) {
var intervalid = setInterval(function () {
var ele = $(selector);
if (ele.length > 0) {
ele[0].click();
clearInterval(intervalid);
return true;
}
}, 500);
} else {
ele[0].click();
return true;
}
}
the problem is in some cases , its not working. however this is an interval , and it's checking the element to be ready every 0.5 sec, so how can it be possible ? is there any other way to check the element is ready ?
additional note:
I have an accordion. I have a function to open the accordion->open one of the items->open the tab page in detail section
this is the function :
//--reach to this point, open accordion index 2--------
ShowAccordion(2);
//----open the item with specific Id in accordion items------
setTimeout(function () {
var selector = "tr[gacategory = '/myprotection/mywills/item_" + parseInt(willId) + "]";
MonitorAndClick(selector);
}, 500);
the point is this element SHOULD be there , sometimes its not loading fast enough , and I WANT TO HAVE A WAY TO CHECK IF ITS LOADED, THEN CLICK ON THAT.
Updated code after comments
var selector = "tr[gacategory = '/myprotection/mywills/item_" + parseInt(willId) + "]";
$("#selector").ready(function () {
console.log('**********.... selector is loaded ....*****');
if (!$("#selector").hasClass('selected'))
MonitorAndClick(selector);
});
still not working.
Why do you want to rely on 0.5 seconds delay to make sure your element is present in DOM. You should be invoking this function only after your element is present in the DOM. If there is another condition that drives when this element is added to the DOM, then call this function once that condition is achieved.
You may want to try https://api.jquery.com/ready/
It seems like jquery ready function can be applied on individual elements too

setInterval triggers function multiple times

EDIT: what i mean by fires multiple times, is that newjob() will fire 3 times, every 5 seconds...so in 20 seconds i'll have it 12 times triggered, instead of the 4 times that i would want. so it's triggeres multiple times every 5 seconds, instead of once every 5 seconds.
I have a function that i created using Toastr to display a message on my web application. i'm eventually going to tie it to an ajax request to an API to determine whether or not to display a message, but for now i'm just testing how it looks.
i am setting an interval, but it fires the function inside of it multiple times (usually 3).
$(document).ready(function() {
setInterval(function () {
newJob();
}, 5000);
});
i can't do setInterval( function(e) { } as e is undefined, as there is no event associated with it, on click, i've used e.stopImmediatePropagation(); to have it only fire once.
how can i stop this immediate propagation on set interval if i don't have e?
thank you.
EDIT: full code:
var newJob = function(e) {
var i = -1;
var $toastlast;
var getMessage = function () {
var msgs = ["There's a new job in the job dispatch queue", "A job pending approval has timed out"];
i++;
if (i === msgs.length) {
i = 0;
}
return msgs[i];
};
var shortCutFunction = "success"; // 'success' or 'error'
toastr.options = {
closeButton: true,
progressBar: true,
debug: false,
positionClass: 'toast-top-full-width',
onclick: null,
timeOut: "0",
extendedTimeOut: "0",
showDuration: "0",
hideDuration: "0",
showEasing: "swing",
hideEasing: "linear",
showMethod: "fadeIn",
hideMethod: "fadeOut",
};
toastr.options.onclick = function () {
window.location.href = "/dispatcher";
};
var msg = getMessage();
$("#toastrOptions").text("Command: toastr["
+ shortCutFunction
+ "](\""
+ msg
+ "\")\n\ntoastr.options = "
+ JSON.stringify(toastr.options, null, 2)
);
var $toast = toastr[shortCutFunction](msg);
};
$(document).ready(function() {
setInterval(function () {
console.log('set interval');
newJob();
}, 5000);
});
and this is my index.phtml file:
<?php
echo $this->headScript()->appendFile($this->basePath() . '/plugins/toastr/toastr.js')
echo $this->headScript()->appendFile($this->basePath().'/js/dispatchernotification.js');
?>
all i'm doing is adding the javascript of what i want running to my index.phtml file and the toastr library.
by console.loging inside interval, i get three logs.
here's a fiddle..not sure how to run it though as it's on ready
http://jsfiddle.net/efecarranza/rfvbhr1o/
setInterval will continue endlessly. I think you're looking for setTimeout.
Make sure to put your setInterval outside of $(document).ready(function() {...}). So it will be like:
<script>
$(document).ready(function() {
... some code ...
});
var myInterval;
clearInterval(myInterval);
myInterval = setInterval(function() {
... your code is here ...
}, 5000);
</script>
For some reason, if it's within $(document).ready() every time you dynamically bring the same page again it double-sets the setInterval in progression and clearInterval function doesn't help until you actually refresh the browser.
setInterval: call a function repeatedly every x milliseconds
setTimeOut: call a function after x milliseconds.
You have two options:
Clear the interval when it isn't necessary anymore:
var intervalId;
$(document).ready(function() {
intervalId = setInterval(function () {
newJob();
}, 5000);
});
// At some other point
clearInterval(intervalId);
Or, the simpler solution in your case, use setTimeout:
$(document).ready(function() {
setTimeout(function () {
newJob();
}, 5000);
});
It would help if you can add a jsfiddle with your code so we can see what's going wrong exactly. It's possible that for whatever reason the setInterval function is being called multiple times. Try adding a console.log statement at the start of that function to check if that's the case.
If it is and you can't figure out why (and neither can we without knowing your code), you could place a check at the start of the function like this:
if (typeof this.installInterval.done == "undefined") {
/*a bunch of code*/
this.installInterval.done = true
}
May be by mistake you are calling your script twice as I did!
In the code below I have called 'testLoop.js' two times.
<script src="../js/testLoop.js"></script>
<script type="text/javascript" src="../js/testLoop.js"></script>
<script type="text/javascript" src="../js/cube.js"></script>

does jQuery stop() work on custom functions?

There are three images that I have made a tooltip for each.
I wanted to show tooltips within timed intervals say for 2 seconds first tooltip shows and for the second interval the 2nd tooltips fades in and so on.
for example it can be done with this function
function cycle(id) {
var nextId = (id == "block1") ? "block2": "block1";
$("#" + id)
.delay(shortIntervalTime)
.fadeIn(500)
.delay(longIntervalTime)
.fadeOut(500, function() {cycle(nextId)});
}
now what i want is to stop the cycle function when moseover action occurs on each of the images and show the corresponding tooltip. And again when the mouse went away again the cycle function fires.
If I understand everthing correctly, than try this code. Tt stops the proccess if you hover the image and continues if you leave the image. The stop() function will work on custom functions if you implement them like the fadeOut(), slideIn(), ... functions of jquery.
$('#' + id)
.fadeIn(500, function () {
var img = $(this).find('img'),
self = $(this),
fadeOut = true;
img.hover(function () {
fadeOut = false;
},
function () {
window.setTimeout(function () {
self.fadeOut(500);
}, 2000);
}
);
window.setTimeout(function () {
if (fadeOut === false) {
return;
}
self.fadeOut(500);
}, 2000);
});​

Javascript "while hovered" loop

Can anybody help me on this one...I have a button which when is hovered, triggers an action. But I'd like it to repeat it for as long as the button is hovered.
I'd appreciate any solution, be it in jquery or pure javascript - here is how my code looks at this moment (in jquery):
var scrollingposition = 0;
$('#button').hover(function(){
++scrollingposition;
$('#object').css("right", scrollingposition);
});
Now how can i put this into some kind of while loop, so that #object is moving px by px for as #button is hovered, not just when the mouse enters it?
OK... another stab at the answer:
$('myselector').each(function () {
var hovered = false;
var loop = window.setInterval(function () {
if (hovered) {
// ...
}
}, 250);
$(this).hover(
function () {
hovered = true;
},
function () {
hovered = false;
}
);
});
The 250 means the task repeats every quarter of a second. You can decrease this number to make it faster or increase it to make it slower.
Nathan's answer is a good start, but you should also use window.clearInterval when the mouse leaves the element (mouseleave event) to cancel the repeated action which was set up using setInterval(), because this way the "loop" is running only when the mouse pointer enters the element (mouseover event).
Here is a sample code:
function doSomethingRepeatedly(){
// do this repeatedly when hovering the element
}
var intervalId;
$(document).ready(function () {
$('#myelement').hover(function () {
var intervalDelay = 10;
// call doSomethingRepeatedly() function repeatedly with 10ms delay between the function calls
intervalId = setInterval(doSomethingRepeatedly, intervalDelay);
}, function () {
// cancel calling doSomethingRepeatedly() function repeatedly
clearInterval(intervalId);
});
});
I created a sample code on jsFiddle which demonstrates how to scroll the background-image of an element left-to-right and then backwards on hover with the code shown above:
http://jsfiddle.net/Sk8erPeter/HLT3J/15/
If its an animation you can "stop" an animation half way through. So it looks like you're moving something to the left so you could do:
var maxScroll = 9999;
$('#button').hover(
function(){ $('#object').animate({ "right":maxScroll+"px" }, 10000); },
function(){ $('#object').stop(); } );
var buttonHovered = false;
$('#button').hover(function () {
buttonHovered = true;
while (buttonHovered) {
...
}
},
function () {
buttonHovered = false;
});
If you want to do this for multiple objects, it might be better to make it a bit more object oriented than a global variable though.
Edit:
Think the best way of dealing with multiple objects is to put it in an .each() block:
$('myselector').each(function () {
var hovered = false;
$(this).hover(function () {
hovered = true;
while (hovered) {
...
}
},
function () {
hovered = false;
});
});
Edit2:
Or you could do it by adding a class:
$('selector').hover(function () {
$(this).addClass('hovered');
while ($(this).hasClass('hovered')) {
...
}
}, function () {
$(this).removeClass('hovered');
});
var scrollingposition = 0;
$('#button').hover(function(){
var $this = $(this);
var $obj = $("#object");
while ( $this.is(":hover") ) {
scrollingposition += 1;
$obj.css("right", scrollingposition);
}
});

jQuery function attr() doesn't always update img src attribute

Context: On my product website I have a link for a Java webstart application (in several locations).
My goal: prevent users from double-clicking, i. e. only "fire" on first click, wait 3 secs before enabling the link again. On clicking, change the link image to something that signifies that the application is launching.
My solution works, except the image doesn't update reliably after clicking. The commented out debug output gives me the right content and the mouseover callbacks work correctly, too.
See it running here: http://www.auctober.de/beta/ (click the Button "jetzt starten").
BTW: if anybody has a better way of calling a function with a delay than that dummy-animate, let me know.
JavaScript:
<script type="text/javascript">
<!--
allowClick = true;
linkElements = "a[href='http://www.auctober.de/beta/?startjnlp=true&rand=1249026819']";
$(document).ready(function() {
$('#jnlpLink').mouseover(function() {
if ( allowClick ) {
setImage('images/jetzt_starten2.gif');
}
});
$('#jnlpLink').mouseout(function() {
if ( allowClick ) {
setImage('images/jetzt_starten.gif');
}
});
$(linkElements).click(function(evt) {
if ( ! allowClick ) {
evt.preventDefault();
}
else {
setAllowClick(false);
var altContent = $('#jnlpLink').attr('altContent');
var oldContent = $('#launchImg').attr('src');
setImage(altContent);
$(this).animate({opacity: 1.0}, 3000, "", function() {
setAllowClick(true);
setImage(oldContent);
});
}
});
});
function setAllowClick(flag) {
allowClick = flag;
}
function setImage(imgSrc) {
//$('#debug').html("img:"+imgSrc);
$('#launchImg').attr('src', imgSrc);
}
//-->
</script>
A delay can be achieved with the setTimeout function
setTimeout(function() { alert('something')}, 3000);//3 secs
And for your src problem, try:
$('#launchImg')[0].src = imgSrc;
Check out the BlockUI plug-in. Sounds like it could be what you're looking for.
You'll find a nice demo here.
...or just use:
$(this).animate({opacity: '1'}, 1000);
wherever you want in your code, where $(this) is something that is already at opacity=1...which means everything seemingly pauses for one second. I use this all the time.
Add this variable at the top of your script:
var timer;
Implement this function:
function setFlagAndImage(flag) {
setAllowClick(flag);
setImage();
}
And then replace the dummy animation with:
timer = window.setTimeout(function() { setFlagAndImage(true); }, 3000);
If something else then happens and you want to stop the timer, you can just call:
window.clearTimeout(timer);

Categories