I'm writing because I need to solve this problem. Until recently, the code was working just fine and I've been using it for quite a long time, but yesterday, when I was testing the page, everything changed.
The idea is click on an image with an anchor tag that is going to redirect the user to another page and in doing so, a confirm dialog box should pop up to ask the person whether they want that. I haven't changed anything in the code, so I'm not getting what's happening. Here's the code:
// **JavaScript**
function confPopUp() {
for (var i = 0; i < 6; i++) {
document.getElementsByClassName("redPic")[i].onclick = redConf;
}
}
function redConf() {
var conf = confirm(
"You're about to be redirected to our social media page. Do you accept?"
);
if (conf) {
return true;
} else {
return false;
}
}
window.onclick = confPopUp;
<!-- **HTML** //THERE ARE 5 MORE ELEMENTS WITH THE CLASS NAME "redPic". -->
<img class="redPic" src="images/instagramLogo.png" alt="Instagram Logo">
The problem is that I'm testing it, right now, and it's not working properly, a the day before yesterday it was working fine, only one click and now, it's working as double-click.
I'd appreciate your help, thanks.
When the page first loads, you're setting a single event handler:
window.onclick=confPopUp;
Later, when there's a click anywhere in the window, that runs your confPopUp function, which hooks up the click handlers on the .redPic elements.
Later, if you click a .redPic element, your redConf function runs.
If you want the .redPic elements to have their handlers hooked up on page load, call confPopUp instead of making it a click handler. Change:
window.onclick=confPopUp;
to
confPopUp();
Be sure this code is running after the .redPic elements exist. There are several ways to do that, pick the one that suits your target browsers and preference:
Put the code in a script tag at the end of the document, just before the closing </body> tag. This works with all browsers, no matter how old.
In even vaguely-modern browsers, call confPopUp from a DOMContentLoaded event handler:
document.addEventListener("DOMContentLoaded", confPopUp);
In modern browsers, add a defer attribute to your script tag.
In modern browsers, add type="module" to your script tag to make your script a module. That defers it just like defer does, and puts it in strict mode (which is a good idea), and put the code in it in module scope rather than global scope (which is really crowded).
So why did it seem to work yesterday? Presumably, because you were clicking the window without realizing it, triggering that initial event handler that hooked up the .redPic elements. Today it just happened that you didn't click the window before trying to click a .redPic element, so you discovered this problem. The problem's been there all along.
Related
I've checked many other answers on StackOverflow but none of them work for some reason.
I'm trying to use something simple like
window.onload = function() {
sleep(5000)
clickButton()
}
But as far as I can tell the button on a page I want clicked loads AFTER page load. So window.onload doesn't work at all. That's why I tried to use a custom sleep function to force the code to run after-after page load but nope. Code "sleeps" by preventing page from fully loading, then runs clickButton(), then the page loads. Useless.
I know my actual button clicking code works in practice because I just fed into the browser console line by line and it worked fine. But the button I'm targeting loads after my code is executed!
I have also tried these which also do not work:
window.addEventListener('load', function () {
clickButton()
})
setTimeout(clickButton(), 5000)
setInterval(clickButton(), 5000)
...
Also I'm using:
document.querySelector("[data-a-target='button-name']");
instead of:
document.getElementById("button-name");
since this button does not have an id.
...
Also I have never used jquery before if that is the answer.
...
How on earth do I get js to click a button immediately as soon as it loads?
The order in which you write your code plays an important role here.
Firstly, put the script tag at the very bottom of the body element of your html page. That forces the browser to have already read through the entire html page before getting to the script tag with your Javascript.
Secondly, I assume you have an event listener for a click on the button. Write the event listener before you let the button be clicked.
For example, I wrote this little code to test my assumption out:
button.addEventListener('click', function () {
console.log('Clicked');
});
button.click();
This should hopefully work for you too. Good luck
I have a rails app, if the user is not logged in, I am redirecting to a page, which has one br tag with a class. Like this
<br class="logged">
In the Javascript on ready of that function, I am triggering a modal as follows.
$(document).ready(function(){
$('.logged').ready(function(){
$('#open-login').click();
});
});
This is working fine, except this modal is getting triggered on every page of the app. I mean that br tag is there in only page of the app, how it is ready for every page is what I don't understand. If anyone can tell what went wrong with my approach, it would be of great help.
ps: It's rails application
You can try this:
$(document).ready(function(){
if ($('.logged').length > 0)
$('#open-login').click();
}
});
Into if condition you can declare an element of specific page and in only that page you can execute an action.
The jQuery .ready() method can only be called on a jQuery object matching the current document. Attaching it to a $('.logged') selector still makes its handler function get called when the document is ready - it doesn't care about the selector.
MarcoSantino's answer will work for your needs, although you may find it cleaner to add the logged-in class to the body tag instead of inserting a new br tag, and then use the following in your JavaScript:
$(document).ready(function(){
if ($(body).hasClass('logged-in')) {
$('#open-login').click();
}
})
I am having a problem on a WordPress site. I have a function which slides down a certain <div>. It is:
jQuery(function($){
$(document).on('click','.tb_usertask_title',function(){
var title = $(this);
var key = title.data('key');
var msg = $('#tb_msg_'+key);
msg.slideDown('fast');
}
});
After executing this function, the <div> slides up again immediately. I think this might be due another script, but I have absolutely no idea how to find which function does this. Is there any way of finding this out? Things I have tried:
Adding breakpoints in my function. This showed me that the folding up happened outside my function.
Using Firebug to break on HTML change. This however redirected to jquery.js, but I did not know how to find out which function triggered the jQuery.
Using Firebug to list the events of my onclick event, but this only showed my function.
These didn't work for me. I also searched for a way to do a function backtrace in Firebug, but without any success.
Use unminified version of jQuery (just for the test and because its more easy to debug).
Look for the dispatch function.
Put a breakpoint in the function where there is an apply usage.
After the code breaks use the F11 to navigate to the binding function.
I'm working on a extension for a fb game that adds some extra info to popup boxes, hides some useless information and run some timers so you can see how long till you have to do something even if you are not on the game page.
My problem is that a while back they went over to using ajax to change between pages and I am wondering if I am using the right approach to handle this.
I run a setInterval that checks if I am on a page where i want to add/remove soemting and i havent done it yet, if this is true I do my stuff, the code looks something like this:
function myFunction() {
if($(selector for some element I am looking for).length > 0 && $(selector for some item I add).length == 0) {
//do some stuff
}
}
setInterval("myFunction()",1000);
Is this the right way of handling ajax page change from an content script in an extension?
If so is there a better way to see if I am on the right page or if i have added to this page already other than doing a selection?
You can use livequery jquery plugin to catch when new element is created on a page:
$("#ajax-element").livequery(function({
//ajax-element is created
});
You can also listen to DOMSubtreeModified event which fires when DOM changes:
document.addEventListener("DOMSubtreeModified", function(event){
//something has changed, possibly ajax-element was added
});
There are also more specific DOMNodeInsertedIntoDocument and DOMNodeRemovedFromDocument events.
I'm using the jQuery dialog plugin.
The dialog div is set up (but not opened) on page load:
$(document).ready(function(){
$('#foo').dialog({autoOpen:false});
});
Then a hyperlink is supposed to open the dialog:
Show dialogue box
But this opens the dialog then a fraction later redirects to a page with the URL javascript:$('#foo').dialog('open');!
I have tried returning false:
Show dialogue box
But then the link doesn't respond at all when I click on it.
I know this must be to do with one of JavaScript's infamous subtleties but I can't work it out.
Can anyone help?
Then a hyperlink is supposed to open the dialog:
Show dialogue box
But this opens the dialog then a fraction later redirects to a page with the URL javascript:$('#foo').dialog('open');!
That shouldn't be happening. The pseudo-protocol javascript: doesn't involve a page load, and certainly not one via HTTP. I don't recommend it (I'd use jQuery's click handler instead), but it should work.
I have tried returning false:
...
But then the link doesn't respond at all when I click on it.
That also shouldn't be happening.
Your code as quoted is fine (works here, for instance: http://jsbin.com/inixa5), so the problem must lie in some other part of the page.
Update: Okay, that's weird, IE6 and IE7 didn't like that; I think it's because dialog returns a value. You can get around that either by wrapping up your call to open the dialog in a function and doesn't explicitly return anything:
Click Me
<script>
$("#foo").dialog({autoOpen: false});
function showDialog(selector) {
$(selector).dialog('open');
}
</script>
Or (and this is mega-hacky) by making sure the last expression in the javascript: block is undefined:
Click Me
<script>
$("#foo").dialog({autoOpen: false});
</script>
Or by using onclick:
Click Me
<script>
$("#foo").dialog({autoOpen: false});
</script>
But in any case, strongly recommend hooking things up with a DOM2 style event handler:
<a href="#" name='openSesame'>Click Me</a>
<script>
// This _can_ be immediately after the anchor, but I'd put it in
// a separate, since .js file for the page that you load just before
// the closing body tag.
$("#foo").dialog({autoOpen: false});
$("a[name=openSesame]").click(function() {
$("#foo").dialog('open');
return false;
});
</script>
Live example (Obviously, you can use any selector that makes sense, you don't have to give the anchor a name [or id].)
One of the nice things about this is that you can then have the anchor take the user somewhere meaningful and/or useful if JavaScript is disabled (something called progressive enhancement).
Change the link to:
<a href="javascript:void(0)" onclick="$('#foo').dialog('open')">
Show dialogue box
</a>
Best avoid putting javascript in the href.
Even better would be giving it a class and than adding a click event to it through jquery.