how to stop the js function on mouse over in it? - javascript

This code dynamically moves some dashboard files within specified interval of time in front end. Now once i move my mouse on any particular dashboard files its not stopping. So suggest me the code to stop the dynamic action on mouse over.
var i=0;
var stp;
var dd = ['/pentaho/content/pentaho-cdf-dd/Render?solution=FPBI&path=%2FDashboards&file=FPBI_Map.wcdf',
'/pentaho/content/pentaho-cdf-dd/Render?solution=FPBI&path=%2Fcss&file=AnalysisBasedonReg.wcdf',
'/pentaho/content/pentaho-cdf-dd/Render?solution=FPBI&path=%2Fcss&file=AnalysisBasedonTime.wcdf'];
function k()
{
self.setInterval("clock()",8000);
}
function clock()
{
document.getElementById('mainfrm').src =dd[i];
i++;
if(i==4)
{
i=0;
}
}
function StopFunction(){
clearInterval(stp);
}
Layout page:
<div class="map">
<body onload="k()" onmouseover="StopFunction()">
<iframe src="/pentaho/content/pentaho-cdf-dd/Render?solution=FPBI&path=%2Fcss&file=FPBIImg.wcdf" style="width:675px;height:690px;overflow:hidden" frameborder='0' id="mainfrm">
</iframe>
</div>
</div>
.
--
Edit
Now onmouseover function is working but when i remove the mouse no action takes place. I tried using onmouseout function. Can anyone suggest me the js function to retain or continue the existing the old one after removing the mouse.

var stp;
function k()
{
stp=setInterval(function(){clock()},8000);
}
function clock()
{
document.getElementById('mainfrm').src =dd[i];
i++;
if(i==4)
{
i=0;
}
}
function StopFunction()
{
clearInterval(stp);
}
<div class="map" onmouseover="StopFunction()">

Try this - complete code - all unobtrusive
Only thing to consider is the global var which is frowned upon
DEMO
<html>
<head>
<script>
var tId, urlIndex=0, dd = ['/pentaho/content/pentaho-cdf-dd/Render?solution=FPBI&path=%2FDashboards&file=FPBI_Map.wcdf',
'/pentaho/content/pentaho-cdf-dd/Render?solution=FPBI&path=%2Fcss&file=AnalysisBasedonReg.wcdf',
'/pentaho/content/pentaho-cdf-dd/Render?solution=FPBI&path=%2Fcss&file=AnalysisBasedonTime.wcdf'];
function clock() {
document.getElementById('mainfrm').src =dd[urlIndex];
urlIndex++;
if(urlIndex>=dd.length) {
urlIndex=0;
}
}
function k() {
tId = setInterval(clock,8000);
}
window.onload=function() {
k(); // start the script
var mapDiv = document.getElementById("mapDiv");
mapDiv.onmouseover=function() {
clearInterval(tId)
}
// the following MAY trigger when over the iframe - remove if necessary
mapDiv.onmouseout=function() {
k();
}
}
</script>
</head>
<body>
<div id="mapDiv" class="map">
<iframe src="/pentaho/content/pentaho-cdf-dd/Render?solution=FPBI&path=%2Fcss&file=FPBIImg.wcdf" style="width:675px;height:690px;overflow:hidden" frameborder='0' id="mainfrm"></iframe>
</div>
</body>
</html>

Related

How to hide a div with a cookie

Hey guys I am currently creating a newsletter popup.
I'm wanting to hide the div after the close button is selected using a cookie. The code snippet I've taken does include some code to try and achieve this but doesn't seem to work for me. Anyone know a solution?
JS
var delay = 0; //in milliseconds
jQuery(document).ready(function($){
setTimeout(function(){
showNewsletterPopup();
}, delay);
jQuery('.popup-close').click(function(){
$('.newsletter-overlay').hide();
});
});
function showNewsletterPopup(){
jQuery('.newsletter-overlay').show();
}
function onLoad() {
var showDiv;
if(localStorage.getItem("showDiv") == null) {
showDiv = true;
}
else {
showDiv = localStorage.getItem("showDiv")
}
if (showDiv) {
document.getElementById('newsletter-overlay').style.display = 'block';
}
else {
document.getElementById('newsletter-overlay').hide();
}
}
function onClose() {
document.getElementById('newsletter-overlay').remove();
localStorage.setItem("showDiv", false);
}
HTML
<div class="newsletter-overlay">
<div id="newsletter-popup">
<img src="/wp-content/uploads/static/TLTX.svg">
<div class="col1">
<div class="newsletter-in">
<h3>Take 10% off your first purchase</h3>
<p class="modalp">Join our Tribe! Our mates get the best rates. Every $1 spent will earn you 1 point. Be the first to know about new arrivals. Receive 10% off your first order! See more on our Tribe page
[wc_reg_form_bbloomer]
</div>
</div>
</form>
</div>
</div>
</div>
the provided code is a bit messy... there are some unused functions and a lot of noise. however, here is my proposal:
$(document).ready(function($) {
const $newsletterPopup = $('#newsletter-popup');
const $newsletterOverlay = $('.newsletter-overlay');
const $popupCloseLink = $('.popup-close');
let showDiv = JSON.parse(localStorage.getItem("showDiv"));
if (showDiv === null) {
showDiv = true;
}
if (showDiv) {
$newsletterOverlay.show();
$newsletterPopup.show();
} else {
$newsletterOverlay.hide();
$newsletterPopup.hide();
}
$popupCloseLink.click(function() {
$newsletterOverlay.hide();
$newsletterPopup.hide();
localStorage.setItem("showDiv", false);
});
});

Iterate through list of url's with start and Stop button

I have a list of URL's and i need it to run as slide show on Start and Stop Of button. Currently it is running as a slideshow with out start and stop button.
Additionally I need to design a homepage with thumbnail of all those URL's.On click of thumbnail it has to redirect to that page
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(function () {
var urls = ["URL1", "URL2", "URL3","URL4", "URL5", "URL6","URL7", "URL8", "URL9"];
var i = 0;
function loadIframe(url)
{
$('#iframe').attr('src', url);
}
setInterval(function() {
// update the index
i = (i + 1) % urls.length;
loadIframe(urls[i]);
}, 13000);
loadIframe(urls[i]);
});
</script>
</head>
<body>
<iframe id="iframe" height="100%" width="100%"></iframe>
</body>
</html>
You need to trigger the setInterval and save it, to clear it later.
var intvl = false; //Global Variable
$('#StartButton').on('click', function()
{
(!intvl) ? intvl = setInterval(...) : return;
});
$('#StopButton').on('click', function()
{
clearInterval(intvl);
intvl = false;
});
EDIT: changed to disable multiple intervals
You can achieve this by storing setInterval in a variable so that you can use clearInterval() on it. clearInterval() will allow you to stop/pause the setInterval you created.
You also don't need the $(function() {...}) component anymore as you will be the one controlling when the slider starts/stops:
var slideInterval;
var urls = ["URL1", "URL2", "URL3", "URL4", "URL5", "URL6", "URL7", "URL8", "URL9"];
var i = 0;
function loadIframe(url) {
//$('#iframe').attr('src', url);
$('#iframe').html(url);
}
function start() {
if (!slideInterval) { // If an interval is already in-use (ie if the slider is running) don't allow another slider to be made -> continue using the current one.
slideInterval = setInterval(function() {
// update the index
i = (i + 1) % urls.length;
loadIframe(urls[i]);
}, 1000);
}
}
function stop() {
if (slideInterval) { // If an interval doe exsist, we can then clear it, if it doesn't exsist then we have no interval to "clear", and so we don't run this code if one isn't in use
clearInterval(slideInterval);
slideInterval = null;
}
}
loadIframe(urls[0]);
#iframe {
border: 1px solid black;
}
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<div id="iframe" height="100%" width="100%"></div>
<button onclick="start()">Start</button>
<button onclick="stop()">Stop</button>

Element changed only once in JavaScript function

I am trying to make an element 'vibrate' using JavaScript upon clicking it by repetitively changing the value of document.getElementById("ElementID").style.left. I change it a number of times in a particular function, but instead of moving each time I change it, it only moves at the end of the function i.e. the last time I make the change. Here is the HTML code:
<html>
<body>
<script>
function changePosition() {
if (document.getElementById("ElementID").style.left == "50%") {
document.getElementById("ElementID").style.left = "52%";
} else {
document.getElementById("ElementID").style.left = "50%";
}
}
function vibrate() {
changePosition();
setTimeout(changePosition, 50);
setTimeout(changePosition, 50);
setTimeout(changePosition, 50);
setTimeout(changePosition, 50);
}
</script>
<button id="ElementID" type="button" style="position:absolute; top:50%; left:50%;" onclick="vibrate()">Vibrate Me</button>
</body>
</html>
At the end I only see the position of the button as it should have been but I can't see the transition during the change. What am I doing wrong?
It seems that all timeouts will execute at the same time. Try changing to this
setTimeout(changePosition,100);
setTimeout(changePosition,200);
setTimeout(changePosition,300);
setTimeout(changePosition,400);
or
for (var i = 1; i < 5; i++) {
setTimeout(changePosition,100*i);
}
Heres an example using setInterval rather than timeout. Mess with the numbers and you should be able to get your desired result
http://jsbin.com/oSIXayun/4/
HTML:
<button id="ElementID" type="button" style="position:absolute; top:50%; left:50%;">Vibrate Me</button>
JS:
function changePosition() {
if (document.getElementById("ElementID").style.left=="50%") {
document.getElementById("ElementID").style.left="52%";
}
else {document.getElementById("ElementID").style.left="50%";}
}
function vibrate() {
changePosition();
setTimeout(changePosition,50);
setTimeout(changePosition,100);
setTimeout(changePosition,150);
setTimeout(changePosition,200);
}
document.getElementById("ElementID").onclick = vibrate;
:)
All the setTimeout calls within vibrate() are made at the same time. You can address this by calling changePosition() based on the number of vibrations you require and repeating the function using setTimeout.
(function () {
var vibrating = 0;
function changePosition() {
if (document.getElementById("ElementID").style.left == "50%") {
document.getElementById("ElementID").style.left = "52%";
} else {
document.getElementById("ElementID").style.left = "50%";
}
if (vibrating != 0) {
vibrating--;
var t = setTimeout(changePosition,50);
}
}
function vibrate() {
vibrating = 4;
changePosition();
}
document.getElementById('ElementID').onclick = vibrate;
})();

Pause Javascript for a few seconds on click

Ok i know this has to be a topic discussed earlier, but all the answers I found were a little complicated considering I'm new and still in the process of learning javascript.
I have the following code in the head section of my html
<script>
function timedText() {
setTimeout(function(){displayResult()},3000);
setTimeout(function(){displayResult1()},7000);
setTimeout(function(){displayResult2()},15000);
setTimeout(function(){timedText()},18000);
}
</script>
<script>
function change() {
setTimeout(function(){timedText()},1000);
}
</script>
<script>
function displayResult() {
document.getElementById("adimg_holder").style.bottom="0px";
document.getElementById("button1").style.backgroundPosition="bottom";
document.getElementById("button2").style.backgroundPosition="top";
document.getElementById("button3").style.backgroundPosition="top";
}
function displayResult1() {
document.getElementById("adimg_holder").style.bottom="370px";
document.getElementById("button1").style.backgroundPosition="top";
document.getElementById("button2").style.backgroundPosition="bottom";
document.getElementById("button3").style.backgroundPosition="top";
}
function displayResult2() {
document.getElementById("adimg_holder").style.bottom="739px";
document.getElementById("button1").style.backgroundPosition="top";
document.getElementById("button2").style.backgroundPosition="top";
document.getElementById("button3").style.backgroundPosition="bottom";
}
</script>
and the following html
<body onload="change()">
<div class="banner_area">
<div class="banner_wrapper">
<img src="images/image_holder.png" />
<div id="ad_holder">
<div id="adimg_holder">
<img class="ad_images" src="images/recruitment_banners.png" />
<img class="ad_images" src="images/training_banners.png" />
<img class="ad_images" src="images/staffing_banner.png" />
</div>
</div>
<div id="ad_buttons">
<div id="button1" style="background-image:url(images/buttonfirst.png);background-position:bottom;width:259px;height:41px" onclick="displayResult()"></div>
<div id="button2" style="background-image:url(images/buttonsecond.png);width:259px;height:41px" onclick="displayResult1()"></div>
<div id="button3" style="background-image:url(images/buttonthird.png);width:259px;height:41px" onclick="displayResult2()"></div>
</div>
</div>
</div>
So the buttons toggle different positions, and the script cycles through the positions at time intervals
Now what I'm trying to achieve is that when the positions are being cycled through, if I click on one of the button, it jumps to the related position and stays that way for a while (say a few seconds) and then continue with the loop.
Hope I've made my motive easy to understand.
Here is how you can achieve this behavior: http://jsfiddle.net/PcZsT/12/
Here is the JavaScript:
function timedText() {
setTimeout(function() {
displayResult();
},2000);
setTimeout(function() {
displayResult1();
},6000);
setTimeout(function() {
displayResult2();
},14000);
setTimeout(function() {
timedText();
},15000);
}
(function change() {
setTimeout(function() {
timedText();
},1000);
}());
var locked = false;
function button1Handler() {
moveTop();
lockFor(3);
}
function button2Handler() {
moveBottom();
lockFor(3);
}
function lockFor(seconds) {
locked = true;
setTimeout(function () {
locked = false;
}, seconds * 1000);
}
function displayResult() {
if (locked) return;
moveTop();
}
function moveTop() {
document.getElementById("adimg_holder").style.bottom="0px";
document.getElementById("button1").style.backgroundPosition="bottom";
document.getElementById("button2").style.backgroundPosition="top";
document.getElementById("button3").style.backgroundPosition="top";
}
function displayResult1() {
if (locked) return;
moveMiddle();
}
function moveMiddle() {
document.getElementById("adimg_holder").style.bottom="370px";
document.getElementById("button1").style.backgroundPosition="top";
document.getElementById("button2").style.backgroundPosition="bottom";
document.getElementById("button3").style.backgroundPosition="top";
}
function displayResult2() {
if (locked) return;
moveBottom();
}
function moveBottom() {
document.getElementById("adimg_holder").style.bottom="739px";
document.getElementById("button1").style.backgroundPosition="top";
document.getElementById("button2").style.backgroundPosition="top";
document.getElementById("button3").style.backgroundPosition="bottom";
}
The functions above are the click handlers of respectively button1 and button2.
I've also changed the change function to бe IIFE (Immediately Invoked Function Expression) but it's not necessary, you don't have to do it because you want to be invoked onload.
you don't need so much code : just make one displayResult function that will call itself over and over :
var scrollParam = { scrollPos : 0, // current pos
scrollIncr : 370, // incr in px each call
loopScrollAfter : 700 // set scrollPos to >0 if above that number
delay : 3000, // std scroll delay
whichIsOnTop : 0, // index of the topmost item (button)
pauseDelay : 1000, // added delay if someone clicks
pauseRequired : 0 }; // current required click delay
var mainItem = document.getElementById("adimg_holder");
function displayResult()
{
mainItem.style.bottom=scrollParam.scrollPos +"px";
scrollParam.scrollPos += scrollParam.scrollIncr;
if (scrollParam.scrollPos>scrollParam.loopScrollAfter) scrollParam.scrollPos=0;
setBackgroundPosition("button1",0);
setBackgroundPosition("button2",1);
setBackgroundPosition("button3",2);
scrollParam.whichIsOnTop = (scrollParam.whichIsOnTop + 1) % 3;
// now setup the next call, taking into account if a pause is required
var requiredDelay = scrollParam.delay;
if (scrollParam.pauseRequired >0) {
requiredDelay += scrollParam.pauseRequired;
scrollParam.pauseRequired=0;
}
setTimeout(displayResult, requiredDelay);
}
var setBackgroundPosition(itemName, index ) {
document.getElementById(itemName).style.backgroundPosition=topOrBottom(index );
};
// returns "top" for the right index (==scrollParam.whichIsOnTop) and "bottom" for the others
var topOrBottom(thisIndex) { return (thisIndex == scrollParam.whichIsOnTop) ? "top" : "bottom"; };
// in the button click handler you should use :
scrollParam.pauseRequired += scrollParam.pauseDelay;
// to launch the scroll, just call :
displayResult(); // in the loaded() event handler for example.
Rq : you can change easily the parameters to have a smoother scrolling if you like.
you can make use of the setTimeout timing function itself.
write a function as:
function calldesiredFunctionafterPause (functionTobeCalled){
setTimeout(function(){functionTobeCalled,1000}) //increase the millisec as needed
}
and on the onClick call this function and pass the function name as parameter.
This will make the onclick function to be delayed for the required time

Is there a way to get all event-listener bindings in Javascript?

I am searching for a way where I can list all event-listener bindings that are made with JS (or other scripts as well) on a website. Mainly I want to find out double bindings (for debug reason), but I guess there are other issues for it as well.
Brilliant would be a plugin for the browser, where you can see on the website which elements have which kinds of eventlisteners bound. You know, some visualization of the event-listeners...
Visual Event (http://www.sprymedia.co.uk/article/Visual+Event+2) is very helpful. Go to this page and just drag the "Visual Event" link into your bookmark bar. When you want to check a page, just click it, wait a second, and the events for each element will be overlaid on the page.
There's only one type of event declaration that you get it, I don't know if this will help you:
// Can't get
myDiv.attachEvent ("onclick", function () {alert (1)});
// Can't get
myDiv.addEventListener ("click", function () {alert (1)}, false);
// Can't get
<div onclick = "alert (1)"></div>
// Can get
myDiv.onclick = function () {alert (1)}
You may look this answer too. Anyway I made a function for you:
<!DOCTYPE html>
<html>
<head>
<script>
function getAllEvents () {
var all = document.getElementsByTagName ("*");
var _return = "";
for (var i = 0; i < all.length; i ++) {
for (var ii in all[i]) {
if (typeof all[i][ii] === "function" && /^on.+/.test (ii)) { // Unreliable
_return += all[i].nodeName + " -> " + ii + "\n";
}
}
}
return _return;
}
document.addEventListener ("DOMContentLoaded", function () {
var div = this.getElementsByTagName ("div")[0];
div.onclick = function () {
alert (1);
}
div.onmouseout = function () {
alert (2);
}
alert (getAllEvents ());
}, false);
</script>
<style>
div {
border: 1px solid black;
padding: 10px;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
I just wrote a script that lets you achieve this. It gives you two global functions: hasEvent(Node elm, String event) and getEvents(Node elm) which you can utilize. Be aware that it modifies the EventTarget prototype method add/RemoveEventListener, and does not work for events added through HTML markup or javascript syntax of elm.on_event = ..., works only for add/RemoveEventListener.
More info at GitHub
Live Demo
Script:
var hasEvent,getEvents;!function(){function b(a,b,c){c?a.dataset.events+=","+b:a.dataset.events=a.dataset.events.replace(new RegExp(b),"")}function c(a,c){var d=EventTarget.prototype[a+"EventListener"];return function(a,e,f,g,h){this.dataset.events||(this.dataset.events="");var i=hasEvent(this,a);return c&&i||!c&&!i?(h&&h(),!1):(d.call(this,a,e,f),b(this,a,c),g&&g(),!0)}}hasEvent=function(a,b){var c=a.dataset.events;return c?new RegExp(b).test(c):!1},getEvents=function(a){return a.dataset.events.replace(/(^,+)|(,+$)/g,"").split(",").filter(function(a){return""!==a})},EventTarget.prototype.addEventListener=c("add",!0),EventTarget.prototype.removeEventListener=c("remove",!1)}();

Categories

Resources