Only run function on button press - javascript

I have a script which checks for an image and then loads a page if it has been found.
I am trying to attach the function to a button so that it only checks when the button is pressed rather than on page load.
<input type="button" id="ImgLoad" value="Check connection">
At the moment, the page redirects on load and is not attached to the button press. I'm struggling to see where I've gone wrong with it.
<script>
networkdelay = window.setTimeout(function()
{window.onclick=encaseimage()}, 1000);
</script>
<script>
clickdelay = window.setTimeout(function(){window.onclick=autoc()},
1000);
</script>
<script>
function encaseimage(){
function ImgLoad(myobj){
var randomNum = Date.now() || new Date().getTime();
var oImg=new Image;
oImg.src="http://192.168.8.1/images/ping2.jpg"+"?rand="+randomNum;
oImg.onload=function(){window.location.href = "/status.html";}
}
networkchecker = window.setInterval(function()
{window.onclick=ImgLoad()},1000);
}
</script>

You are calling the function instead passing the function reference:
window.onclick=ImgLoad()
Should be:
window.onclick=ImgLoad
Otherwise the ImgLoad function runs immediately.
I should say that adding onclick to window is probably not the best design (depending on what you are doing). Usually, you would look up the button (by id perhaps) and attach a click handler only to that particular button.
On a side note, it looks like the other window.onclick events are also setting to the result of calling a function:
window.onclick=encaseimage()}, 1000);
window.setTimeout(function(){window.onclick=autoc()},
You may want to review those as well. :)

If you want to load image on button click you need to attach that to the button click event.
like
$("#ImgLoad").click(function(){
var randomNum = Date.now() || new Date().getTime();
var oImg=new Image;
oImg.src="http://192.168.8.1/images/ping2.jpg"+"?rand="+randomNum;
oImg.onload=function(){window.location.href = "/status.html";}
});

Related

window.onload function is called on page load and also every time I close an overlay

I have some JS code that I am trying to debug, and the problem is that the window.onload function is being called way more often than I expect it to. Here is my JS code:
var trueCountApp = (function(){
window.onload = function(){openRulesOverlay()};
document.getElementById("open-rules-overlay-button").onclick = function(){openRulesOverlay()};
document.getElementById("select-rules-button").onclick = function(){saveRuleSelections()};
function openRulesOverlay(){
let blackjackRules;
if(sessionStorage.blackjackRules){
blackjackRules = JSON.parse(sessionStorage.blackjackRules);
for(let i=0; i<blackjackRules.length;i++){
document.getElementsByClassName("rule")[i].value = blackjackRules[i];
}
}
document.getElementById("rules_overlay").style.display = "block";
}
function saveRuleSelections(){
let blackjackRules = [];
let rules = document.getElementsByClassName("rule");
for(let i=0; i<rules.length;i++){
blackjackRules.push(rules[i].value);
}
let jsonBlackjackRules = JSON.stringify(blackjackRules);
sessionStorage.setItem("blackjackRules", jsonBlackjackRules);
document.getElementById("rules_overlay").style.display = "none";
}
})();
There are 2 buttons on my page: one opens an overlay, and the other closes an overlay. I also wanted to run some code a single time when the page is first loaded, and I just used the openRulesOverlay() function that I had already written as a placeholder for the code I want to run. What I expected to happen was for the page to load, openRulesOverlay() would run once, then the buttons would work as normal from there. However, it seems that the window.onload function is running anytime the overlay gets closed. Why is this happening?
Note: I did not include the html code because I didn't think it was relevant to this problem. Let me know if I need to include it.
Simple fix in my particular case: the default button type is "submit", so the page would load, the form would open, and then when I pressed a button to close the form, it was essentially reloading the page and opening the form again. Just needed to change button type to "button".

Disqus not firing when button clicked

Does anyone have experience with Disqus?
I am adding buttons to the existing website and when button is pressed, it should fire disqus comments.
In the beginning, this is run
function insertdisqus(){
var dsq = document.createElement('script');
dsq.type = 'text/javascript';
dsq.async = true;
dsq.src = 'https://myforum.disqus.com/embed.js';
$('head').append(dsq);
}
then,
var button = document.createElement("a");
button.setAttribute("id", "diqus");
button.innerHTML = "Discussion";
button.addEventListener('click', loaddisqus);
function loaddisqus(e){
parent_element = $(this).parent().parent();
next_element = parent_element.next();
subjectcode = next_element.attr('data-subjectcode');
var disqus_identifier = subjectcode;
var disqus_url = window.location.origin;
next_element.after('<div id="disqus_thread"></div>');
so, when the button is pressed, loaddisqus should execute, and it does. But it doesn't do anything further than creating the disqus_thread divs...
What could be wrong?
first thing, you try to mix plain javascript and jquery (not a good idea)
perhaps you can try something like this:
var btn = $('<button>').html('Duscussion').on('click', btnClickListener);
$('body').append(btn);
var btnClickListener = function(event){
var clickedElement = $(this); // get the clicked element
clickedElement.html('new Text'); // do what you want (i.e. change the content of the clicked button)
}
second is, you try to use a link (a-tag) as an button. the problem is, a link allways tries to relocate your page to the href target. a button should be a button, not a link. if you need a link because of style or something you have to expend your listener function to something like this:
var linkButton = $('<a>').attr('href', '#').html('click here').on('click', linkButtonListener);
$('body').append(linkButton);
var linkButtonListener = function(event){
event.stopPropagation(); // stops actions from all parent elements
event.preventDefault(); // stops the default actions of the link
var clickedButton = $(this); // get the clicked element
clickedButton.html('allready clicked'); // do what you want (i.e. change the content of the link)
}
i hope that helps you to understand how the listeners with jquery works very simple.
last thing, you try to enable a script tag and hope the script runs after click on your button. but this does not work in javascript. all scripts will be loaded once. you can't execute it by adding a script tag after the document is ready. if you want this, you have to execute it by hand (perhaps with eval function), but it's not the fine way. There are some frameworks that can include scripts by action and make them executeable i think. i know it does not work and never used it.

How can I redirect to home page after video stops

I am using Cincopa to embed my video into my website. The page that it is embedded in is hidden and navigation is removed. So I would like everyone to be redirected to the home page once the video is finished.
Here is my code:
<div id="cp_widget_55a42f1b-6e51-4738-87f9-eaf52dc6a826">...</div>
<script type="text/javascript">
var cpo = [];
cpo["_object"] = "cp_widget_55a42f1b-6e51-4738-87f9-eaf52dc6a826";
cpo["_fid"] = "AsBAj2M3MQOr";
var _cpmp = _cpmp || [];
_cpmp.push(cpo);
(function() {
var cp = document.createElement("script");
cp.type = "text/javascript";
cp.async = true;
cp.src = "//www.cincopa.com/media-platform/runtime/libasync.js";
var c = document.getElementsByTagName("script")[0];
c.parentNode.insertBefore(cp, c);
})();
</script>
<noscript>Powered by Cincopa <a href='http://www.cincopa.com/video-hosting'>Video Hosting for Business</a> solution.<span>Test</span><span>bitrate</span><span> 39961 kb/s</span><span>height</span><span> 1080</span><span>duration</span><span> 00:02:35.31</span><span>lat</span>:<span> +33.2269</span><span>long</span>:<span> 21-96.93</span><span>fps</span><span> 59.94</span><span>width</span><span> 1920</span><span>originaldate</span><span> 2015-06-06 19:08:58</span>
</noscript>
Cincopa embeds a video HTML tag, you have to add an event as explained here
Well, right now I'm not quite in the mood to make a complete test, so I'll just suggest a workaround which you will need to adapt.
In order to give you the exact code, I need to know:
What CMS are you using?
Can you add an id or a class to your video tag with cincopa?
Are you including jQuery?
Then you'll have to add this lines in the bottom of your script:
//Wait until the page is entirely loaded, and so you can access the rendered video tag (you'll need jQuery)
$( document ).ready(function() {
function goHomeYouAreDrunk(e) {
window.location.href = "http://url.to.your.home.page";
}
//I'm supposing that your video is the sole video tag in your page, if it's not, you'll have to get it by its id or class
document.find('video').addEventListener('ended',goHomeYouArDrunk,false);
});
Normally, that would be via an event listener on the <audio> or <video> element.
How to add Event Listeners | W3Schools : https://www.w3schools.com/Jsref/met_element_addeventlistener.asp
But a way I'd do it with Javascript just to be sure is:
// The interval clocks every .1 second(s).
setInterval(function() {
// If the element's current playback time is the playback duration (has reached the end).
if (audioElement.currentTime == audioElement.duration)
doSomething()
}, 100)
Although if you are wary about performance and don't want to use a setInterval() function, then stick with adding an event to the element.
By the way, to re-direct to another page, use the Javascript function location.assign("https://www.example.com.").
This code has been tested in https://www.cincopa.com/:
document.getElementById("video_iframe_id_in_your_page")
.contentWindow
.document.getElementsByTagName("video")[0]
.addEventListener("ended", function(args){
window.open("/", "_top");
});
wish can help you.
You can redirect to the home page by setting window.location="/"
I'm not sure how you're checking if the video has ended, you can add a listener like this.
Upon completion, you can call a handler function to redirect the user to the homepage.
document.getElementById('myVideo').addEventListener('ended',redirectToHomePage,false);
redirectToHomePage(){
window.location = "/";
}

JavaScript continuously executing and then stops

I created a js file and created a function and what it supposed to do is change the image once everytime my page is loaded..
function swapPic() {
var imgSrc = [];
imgSrc[0] = "/Content/Resources/cafe1.jpg";
imgSrc[1] = "/Content/Resources/cafe2.jpg";
imgSrc[2] = "/Content/Resources/cafe3.jpg";
imgSrc[3] = "/Content/Resources/cafe4.jpg";
imgSrc[4] = "/Content/Resources/cafe5.jpg";
imgSrc[5] = "/Content/Resources/cafe6.jpg";
var randomnumber = Math.floor(Math.random() * 5);
var img = document.getElementById("imgContainer");
img.setAttribute("src", imgSrc[randomnumber]);
// alert("ok");
}
In my html code, in my img tag:
<img id="imgContainer" src="~/Content/Resources/cafe3.jpg" onload="swapPic()"/>
Adding the alert("ok") line and i reload the page once, the alert window keeps popping up and the image changes. I keep closing the window, and it still pop ups and the image changes. It just stopped after some time.
So I guess, during the time i did not include that alert("ok") line, my function is continuously called and stop. It just happen so fast which makes it look like fine.
I think this is a problem. Do you have any idea guys how can I make sure that my function is just called once?
You should add onloadon the body, not the img.
<body onload="swapPic();">
<img id="imgContainer" src="~/Content/Resources/cafe3.jpg"/>
</body>
If you add onload to the img, then the function will be called each time the image is loaded, which causes an infinite loop.
If you cannot modify the body tag, then replace your current function swapPic() with this:
(function swapPic() {
var imgSrc = [];
imgSrc[0] = "/Content/Resources/cafe1.jpg";
imgSrc[1] = "/Content/Resources/cafe2.jpg";
imgSrc[2] = "/Content/Resources/cafe3.jpg";
imgSrc[3] = "/Content/Resources/cafe4.jpg";
imgSrc[4] = "/Content/Resources/cafe5.jpg";
imgSrc[5] = "/Content/Resources/cafe6.jpg";
var randomnumber = Math.floor(Math.random() * 5);
var img = document.getElementById("imgContainer");
img.setAttribute("src", imgSrc[randomnumber]);
// alert("ok");
})();
This will execute it exactly once. No need to call it anywhere.
images have their own load event that refers to when the image finishes loading. so, each time you update the src, the browser of course starts loading the image, and fires the event again once it finishes loading it. the cycle repeats.
You could use window.onload to call your function just once, because the window's load event can only happen once.
You've attached onload to an image. In this case swapPic() will be called on every image load. So, what happens is an endless loop - you call swapPic(), it loads a new image which triggers again swapPic(). For more information look at W3Schools: Event - Img Onload.
You should move the swapPic() to body. This will trigger swapPic() only when the body is loaded.
Another way is to use javascript:
// if you have jQuery
$(document).ready(function(){
swapPic()
});
// ordinary javascript
window.onload = function() {
swapPic();
}
Use the onload function in tab. BTW according to your code your imgSrc[5] = "/Content/Resources/cafe6.jpg"; will never be shown as your random function only generates 0-4.
it should be
var randomnumber = Math.floor(Math.random() * 6);

Refresh contents of div after loading with click function

I have a page laid out with 2 Div's on the page. The first Div works fine and loads a list of players. Now when you click on a link in that Div, it loads a second Div with information about that player. That too works fine, but what I want to do is have that second Div periodically refresh that players data after it being loaded by the click event. Here was my current attempt but it's not working:
var loc = "";
$("a").live('click', function() {
loc = "player.php?user=" + $(this).html();
$("#result").load(loc);
});
setInterval(function() {
$("#results").load(loc);
}, 1000);
Try moving the setInterval inside the click event handler so that it doesn't fire off before the first click and you ensure the loc is defined before the first interval completes.
Also, you may have a typo within your setInterval, as it refers to $('#results'), not $('#result'). One or the other is likely incorrect.
Finally, it's good practice to assign a setInterval to a variable, so that you can clear it later, if needed with clearInterval. it also lets you set the interval just once, rather than every time the user clicks
var loc = "";
var interval = null;
$("a").live('click', function(){
loc = "player.php?user=" + $(this).html();
$("#result").load(loc);
// only create the interval once
if(!interval) {
interval = setInterval(function(){
$("#result").load(loc);
}, 1000);
}
});
You are assigning the url to loc in click event of anchor a which would be loading the contents but the other case of setInterval which is executed on load the loc will not have the url. So assign url to loc the time you declare it or make sure it is assigned before setInterval.
Also note live is deprecated you should use on instead.
var loc = "player.php?user=" + $("a").html();
$("a").live('click', function(){
loc = "player.php?user=" + $(this).html();
$("#result").load(loc);
});
setInterval(function(){
$("#results").load(loc);
}, 1000);

Categories

Resources