click function doesnot work after auto page refresh - javascript

I am refreshing my page every 25 seconds using Javascript.But another Javascript for click function works fine before page refresh whereas after page refresh it doesnot work.
HTML:
<div id="refreshOnline">
<div id="refreshData">
//Set of Functions
<a target="_blank" href="http://example.com/startgame.php?gname='.$key['gameName'].'&player='.$_SESSION["uname"].'&type=t20" class="btn btn-primary btn-sm popup-game" id="popup-game" >Play Now!</a>
</div>
</div>
Javascript:
<script type="text/javascript">
//Script to refresh Div
function show_data()
{
$('#refreshOnline').load('main.php #refreshData');
}
setInterval('show_data()', 25000);
//Script to oprn link in new window
$('#popup-game').click(function (event) {
event.preventDefault();
alert("Working");
window.open($(this).attr("href"), "popupWindow","width=600,height=600,scrollbars=yes");
});
</script>
Before refresh, link opens in new window whereas after execution of refresh script, link opens in new tab instead of new window.

The code:
$('#popup-game').click(...
binds a click handler to the #popup-game element that exists at the moment that code runs. If that element is a child of #refreshOnline it will be replaced when you refresh #refreshOnline and so the new version of that element will not have a click bound. You can use a delegated event handler instead:
$('#refreshOnline').on('click', '#popup-game', function(event) {
event.preventDefault();
alert("Working");
window.open($(this).attr("href"), "popupWindow","width=600,height=600,scrollbars=yes");
});
This actually binds the handler to #refreshOnline, but when a click occurs jQuery automatically checks if it was on a child element that matches the selector in the second parameter and only calls your function if it does.
For more information see the .on() doco.

This is because the click handler is not assigned to the new content. Set them again after you have changed the content like so:
<script type="text/javascript">
//Script to refresh Div
function show_data()
{
$('#refreshOnline').load('main.php #refreshData');
setClickers();
}
function setClickers(){
//Script to oprn link in new window
$('#popup-game').click(function (event) {
event.preventDefault();
alert("Working");
window.open($(this).attr("href"), "popupWindow","width=600,height=600,scrollbars=yes");
});
}
$(function(){
setClickers();
setInterval('show_data()', 25000);
});
</script>

You should register the click event every time you refresh the content of the div.

Related

Changing <script> tag dynamically with jQuery

I've been trying to figure out if it's possible to dynamically change the src of a <script> tag (or load a new script tag) and have the previous script no longer execute. Example below:
index.html
<button id="action">Click</button>
<script id="javascript-file-script" type="text/javascript" src="/js/oldjsfile.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#javascript-file-script").remove();
setTimeout(function() {
$('body').append('<script id="javascript-file-script" src="/js/newjsfile.js" type="text/javascript"><\/script>')
}, 100);
});
</script>
oldjsfile.js
$(document).ready(function() {
console.log('old file loaded');
$('#action').click(function() {
alert('old');
});
});
newjsfile.js
$(document).ready(function() {
console.log('new file loaded');
$('#action').click(function() {
alert('new');
});
});
Before changing the javascript file, clicking on #action would have 1 alert "old". Once I change the script, and click on #action I get both alerts "old" and "new". Is there a way to "unload" the previous file so that the original click function is removed/not executed?
I'm looking for a solution other than changing ids or editing the scripts. I'm thinking this isn't possible because the script is already in memory.
That isn't possible. It is already loaded and running. You should consider using .on and .off for binding to the click event.
To begin, you definitely do not want to load and unload scripts as that will cause other problems and loading scripts should be done asynchronously.
For your first event, you did everything fine.
For the second event, it has to happen when something else happens. In my snippet below, I created another button and when that was clicked it took off the old event and added the new one. This doesn't have to happen on button click it can be on anything but you have to remove the old event with unbind and create a new one just like you did originally.
To try the example below, click the first button and you'll see an alert of 'old'. Then click on the second button and click on the first button again and you'll see 'new'.
$(document).ready(function () {
// The original click event.
$('#action').click(function () {
alert('old');
});
// Let's set up a reference to our new button which will cause the #action click to change.
$('#changeAction').click(function () {
// Unbind the previous click event associated with #action:
$('#action').unbind('click');
// Create the new click event.
$('#action').click(function () {
alert('new');
});
});
});
<button id="action">Click</button>
<button id="changeAction">Click me to change the action of the first button</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

prevent from window.location to child div Jquery

I'm currently working with this code, anytime I click on the div it goes to the url...
HTML
<div class='gotoPost' data-href='post?i=24'>[text]</div>
JQUERY
$(function() {
toUrl = function(){
var GoToUrl = $(this).data('href');
var redirect = GoToUrl;
window.location = redirect;
}
});
$(function() {$(".gotoPost").on('click',toUrl);});
PROBLEM
Now I want to add a absolute-positioned div at the top of the container, but anytime I click on it. (to show a Lightbox) it goes to the url...how do I prevent it from going to the url? I want when clicked the child div,it doesnt go to the url.
<div class='gotoPost' data-href='post?i=24'>[text]
<div class=ShowLightBox>3</div>
</div>
So Your question is..
<div class='gotoPost' data-href='post?i=24'>
[text]
<div class=ShowLightBox>3</div>
</div>
If you click 'showlightbox' div, it doesn't redirect to other page,
but when you click other area of 'gotoPost', then you want to redirect page. right?
Solution
So here's the solution:
$(function() {
toUrl = function(e){
if (e.target.classList.contains('gotoPost')) {
var GoToUrl = $(this).data('href');
var redirect = GoToUrl;
window.location = redirect;
}
}
});
$(function() {$(".gotoPost").on('click', toUrl);});
If you use call-back function with JS, when event happends it will call call-back function with 'EVENT' object, which contains 'e.target' - HTML Element you've click.
the code above check if your click event is targeting 'gotoPost' directly not inside HTML element. So this would work for you! :)
ps. Checkout "Event Delegation with JavaScript".
You need to prevent the click event on .ShowLightBox from propagating. For example:
$('.ShowLightBox').on('click', function(e){
e.stopPropagation();
// Open light box
});
Ref: https://api.jquery.com/event.stoppropagation/

Closing an overlay with an a href

I have a navigation overlay and what I would like to do is close the navigation when a link is clicked. It works with href="#" but my links are href="someplace.com". How can I have the link close my div while still using the href?
`<script>
$(document).ready(function(){
$(".menu-wrapper a").click(function(){
$(".overlay").fadeToggle(200);
$(this).toggleClass('btn-open').toggleClass('btn-close');
});
});
$('.overlay').on('click', function(){
$(".overlay").fadeToggle(200);
$(".menu-wrapper a").toggleClass('btn-open').toggleClass('btn-close');
open = false;
});
</script>`
and the link is
`<li><a class="btn-close" href="<?php echo SITE_URL; ?>profiles">Profiles</a></li>`
Thanks for any help.
If the link has href="#" page doesn't get reloaded, otherwise it would.
You could do this:
<li><a class="btn-close" href="javascript:void(0)" onclick="closeOverlay()">Profiles</a></li>
then write a function
function closeOverlay() {...}
where you would close the overlay and call AJAX to get your PHP data
My Jquery is rusty
$('.some-class-for-all-nav-links').click(function () {
// select the nav and close it with css or javascript
})
Events in a browser cascade down and then up. Say you have the following structure:
<html>
<head>...</head>
<body>
<section>
<p>Here is a link</p>
</section>
</body>
</html>
When you click on the link, the click event is sent to any event listener bound to elements in this order: window, html, body, section, p, a, a, p, section, body, html, window. Whether an event occurs when the event is passing from top to bottom (on capture) or from bottom to top (on bubbling) is determined by setting the onCapture boolean parameter on the addEventListener call.
You could bind an event to the HTML document that is triggered on capture, checks if the user clicked a link and if so, close the nav or whatever it is you want to do. I don't think jquery supports event capturing, you'll have to do it vanilla-style.
Here's some JS following my mockup example. This adds an event listener to the whole document which will fire when a click is detected. It then checks that the thing that was clicked is actually a link (<a> element).
document.addEventListener('click', function (e) {
if (e.target.tagName === 'A') {
alert("You've just clicked a link");
}
}, true); // true to trigger on 'capture'
https://jsfiddle.net/gf9drum2/

Jquery not delaying properly when clicking on <a> tag

I have a div I want to show when I click an <a> tag, I want to wait for like 10 seconds before redirecting, but it just shows me the div and redirects without waiting.
Html code:
<a class="clickHereToDisplay" href="http://www.google.com">Click here to go</a>"
<div class="hiddenDiv"></div>
Jquery code:
<script>
$(document).ready(function(){
window.setTimeout(function(){
$(".clickHereToDisplay").click(function(){
$('.hiddenDiv').text('THE TEXT I WANT TO DISPLAY WHEN THE HREF IS CLICKED');
$('.hiddenDiv').show();
});
}),10000;
});
</script>
The problem is the browser is using the href to immediately redirect. You want something like this:
<a class="clickHereToDisplay" href="#" onclick="timedRedirect()">Click here to go</a>"
<div class="hiddenDiv"></div>
Then your javascript:
var timedRedirect = function() {
$('.hiddenDiv').text('THE TEXT I WANT TO DISPLAY WHEN THE HREF IS CLICKED');
$('.hiddenDiv').show();
window.setTimeout(function(){
window.location.href = "http://www.google.com"
}),10000);
};
One other note; there is nothing preventing the user from doing other stuff in the ensuing 10 seconds, so make sure you handle user flows you don't want occurring (like other event handlers, etc).
You need to use the timeout in the click handler.
In the click handler first you need to show the hidden div and the use a timer to delay the redirection for which you need to prevent the default action of the click and then manually set the location in the timeout handler.
$(document).ready(function () {
$(".clickHereToDisplay").click(function (e) {
e.preventDefault();
$('.hiddenDiv').text('THE TEXT I WANT TO DISPLAY WHEN THE HREF IS CLICKED').show();
window.setTimeout(function () {
window.location = e.currentTarget.href;
}, 10000);
});
});

Automatically update javascript elements when internal Anchor/Hash is clicked

I would like to display the updated Anchor/Hash in id="demo" when a link is clicked. The layout of the document is as follows.
<html>
<head>
<script type="text/javascript">
function myfunction()
{
document.getElementById("demo").innerHTML=location.hash;
}
</script>
</head>
<body>
<h1>Javascript</h1>
<p id="demo">This is a paragraph.</p>
here
</body>
</html>
Only problem is when the link is clicked the javascript does not get the updated Anchor/Hash until the link is pressed for a second time.
It is because the location hasn't changed at this time. Here is a way you can use:
function myfunction() {
// Sets the event handler once you click, so it will execute when
// the hash will change.
window.onhashchange = function() {
document.getElementById("demo").innerHTML=location.hash;
};
}
A modern way would be:
var hashchange;
function myfunction() {
if ( !hashchange ) {
hashchange = addEventListener( 'change', function() {
document.getElementById("demo").textContent = location.hash;
// If you want to remove the event listener right after,
// you can do this:
removeEventListener( hashchange );
}, false );
}
}
Try this JQuery plugin for detecting the hash change:
http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/
It's open-source, so check out the code, which is surprisingly complex-- 300+ lines (annotated, but still).
Try this:
function myfunction() {
setTimeout(function() {
document.getElementById("demo").innerHTML=location.hash;
}, 1);
}
because when you click in the link the hash is still your prevous one so you need a delay.
It is because "location" refers to an anchor WITHIN the page.
The first click, you have no location within the page, but the anchor takes you to #example, but all this happens after the onclick has done its business. The second click we have a location of #example.
See the W3 Schools documentation here.
The onclick event is fired before the anchor has had chance to do its job. This is crucial to being able to cancel the propagation of the event and prevent redirection etc. but sadly knobbles your code.

Categories