Refresh contents of div after loading with click function - javascript

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);

Related

Only run function on button press

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";}
});

How to fade out page A and fade in page B? In javascript only

What I want to do:
On page A, there are links to many pages e.g. page B, page C etc.
When I click on a link, I want the current page to fade out and the new page to fade in.
I searched a lot and got lots of jquery solutions - they work fine but I want to find out how I can do this in vanilla javascript only. I tried to work it out on my own but it doesn't work. I've already checked for console errors and put the JS script in the footer.
document.addEventListener("click", "a", function () {
// get the href attribute
var newUrl = this.attr("href");
// veryfy if the new url exists or is a hash
if (!newUrl || newUrl[0] === "#") {
// set that hash
location.hash = newUrl;
return;
}
// now, fadeout the html (whole page)
document.querySelector("html").fadeOut(function () {
// when the animation is complete, set the new location
location = newUrl;
});
// prevent the default browser behavior.
return false;
});}
Done in vanilla javascript.
When you click on a link, the code snippet delays the default loading of the next page until the fade-out animation is complete.
document.querySelector("a").addEventListener("click", function () {
event.preventDefault();
// get the href attribute
var newUrl = this.getAttribute("href");
document.querySelector("body").addClass("fade-out");
// verify if the new url exists or is a hash
if (!newUrl || newUrl[0] === "#") {
// set that hash
location.hash = newUrl;
return;
}
// now, fadeout the html (whole page). You need to set the duration manually.
//if you have an animation that lasts .5, 1 or 2 seconds etc, you need to put the duration below
var animationDuration = 500;
setTimeout(function() {
location = newUrl;}, animationDuration);
});}
You can use iframe inside modal popup and can open page in it.
See below links for reference :-
load iframe in bootstrap modal

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.

html5 messaging multiple instance

i have a script like this
function resizeCrossDomainIframe(id, other_domain) {
var iframe = document.getElementById(id);
window.addEventListener('message', function (event) {
if (event.origin !== other_domain) return; // only accept messages from the specified domain
if (event.data === "reload") top.location.reload(); // If child page sends reload request - reload it without any questions asked
if (isNaN(event.data)) { //If this isn't integer than it is alert
alert(event.data); // Show alert if not integer
} else {
var height = parseInt(event.data) + 5; // add some extra height to avoid scrollbar
iframe.height = height + "px";
alert(event.data);
}
}, false);
}
what it does is dynamically resizes iframe. Now On a first iframe page I just get one alert, but in within iframe page i have links and when I go to second page I see 2 alerts, when I go to third page - i get 3 alerts, 4th link trigger 4 alerts etc...
In each iframed page I am calling parent to resize like:
<body class="settingspage" onload="parent.postMessage(document.body.scrollHeight, '<?php echo $_SESSION['SESS_ACCESSING_FROM']; ?>');">
I tried to clear the "event" array, but I still get Alerts, but this time they are empty, but the number of alerts equals the number of link-clicks within the iframe ?
Why is this ?
The problem is, every time you click on a link in the iframe, the load event is fired.
So you bind your message event every time a link is clicked.
On first time everything is correct, because you binded it once, on the second time you get two alerts, because you bound it twice, and so on...
So the solution is to remove the 'message'event on unload of iframe.
For this reason you have to clean your code a bit:
var listener = function (event) {
if (event.data === "reload") top.location.reload(); // If child page sends reload request - reload it without any questions asked
if (isNaN(event.data)) { //If this isn't integer than it is alert
alert(event.data); // Show alert if not integer
} else {
var height = parseInt(event.data) + 5; // add some extra height to avoid scrollbar
iframe.height = height + "px";
alert(event.data);
}
};
then you have your functions which you call onLoad and onUnload.
function iframeOnLoad(id) {
var iframe = document.getElementById(id);
window.addEventListener('message', listener, false);
}
function iframeOnUnload(id) {
var iframe = document.getElementById(id);
window.removeEventListener('message', listener, false);
}
I solved this by moving function to "main page body on load" and removing it from iframe...

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);

Categories

Resources