I am trying to use a userscript to click a button. According to inspect element, the button looks like:
<div class="q-w-btn cl"></div>
Conveniently, the web developer neglected to put an id in there, so I was not able to select it by the id and then use the click function (are they called functions in JavaScript? I'm not an expert in the language).
I have tried many, many, many different ways, and all of them have successfully failed to click the button.
Any help is greatly appreciated, thanks for reading about my problems.
You can get elements by class name as well in java Script like below
document.getElementsByClassName("q-w-btn");
but notice that this function will return all elements in the document having the specified class name in the form of an array. As a result if your document has only one element having this class then you need to get the first element like below.
document.getElementsByClassName("q-w-btn")[0];
And yes in java script it is called functions you can see the conventions in here http://javascript.crockford.com/code.html.
Please try the following code (Insert script before </body>):
var btn = document.querySelector('.q-w-btn.cl');
if (btn) {
btn.addEventListener('click', onButtonClick);
}
function onButtonClick(evt) {
console.log('the click event is trigger');
}
You can simply use document.getElementsByClassName('q-w-btn') and bind click event on it, something like -
var button = document.getElementsByClassName('q-w-btn')[0];
button.addEventListener('click', function () {
alert('here');
});
<div class="q-w-btn">Click me</div>
This (courtesy of Ramin) worked for me:
var btn = document.getElementsByClassName("q-w-btn")[0]; btn.click();
Thanks to everyone who helped me learn and come to this solution.
Related
I'm trying to add an OnClick function to 4 elements element on page load and then make those OnClick functions change the text of a separate element. I tried creating a function called AddClick that specified the elementID and then sets an OnClick attribute and seperate function. (I did this four times for each element I want to have the new function activated on click.
I then asked the AddClick to run on page load.
Then I created the functions that would replace the old text of the seperate element. (These should be set to run when the elements are clicked.
Sorry in advance if this was the wrong approach/If I'm not clear. First time posting on here, any help appreciated.
For the HTML the text I am trying to alter is within a div with an ID, but the h4 does not have a specific ID and I cannot add one.
Here is the JavaScript I tried to implement:
<script type="text/javascript">
function AddClick(){
//Name & Number
document.getElementById("o_5794738").setAttribute('onclick', "NewText()");
//Number
document.getElementById("o_5794733").setAttribute('onclick', "OldText()");
//Name
document.getElementById("o_5794723").setAttribute('onclick', "OldText()");
//None
document.getElementById("o_5794728").setAttribute('onclick', "OldText()");
};
window.onload = AddClick;
function NewText() {
document.getElementById("pt_fc_775338").getElementsByTagName(h4).innerHTML = "<h4>New Text</h4>";
}
function OldText() {
document.getElementById("pt_fc_775338").getElementsByTagName(h4).innerHTML = "<h4>Old Text</h4>";
}
Any help is much appreciated.
You can try this:
document.getElementById("demo").onclick = function() {myFunction()};
I found this example on https://www.w3schools.com/jsref/event_onclick.asp
No need to add click event using load you can directly add the click event using .addEventListener (by the way .setAttribute is not for adding any event)
Simply use .addEventListener like this :
document.getElementById("o_5794738").addEventListener('click', NewText);
Read this for more info about .addEventListener()
Here is the demo snippet below :
document.getElementById("o_5794738").addEventListener('click', NewText);
function NewText() {
document.getElementById("pt_fc_775338").getElementsByTagName("h4")[0].innerHTML = "New Text";
}
<button id="o_5794738">Click Me!</button>
<div id="pt_fc_775338">
<h4></h4>
</div>
I've been looking for so long and found several answers that suggest using .on() as in $('.idOfMyElemenet').on() works even for elements that don't exist yet. But this doesn't seem to be finding the element. Am I doing something wrong?
The highest level <span> (in screenshot) does not exist until I click on a drop-down. Ultimately I'm trying to trigger an event when the user clicks on any of the <li> (aka selects an option from the drop-down).
$(document).ready(function () {
var test = "#select2-id_customer-results";
$(test).on("click", function() {
console.log('hello')
})
})
EDIT:
Thanks to Drew Baker - I think his second solution is the way to go. But not quite there yet...
From the select2 documentation
All public events are relayed using the jQuery event system, and they
are triggered on the <select> element that Select2 is attached to.
So I tried listening to it via the id (which doesn't seem to exist but would probably be id_customer) and the class. The class I added below did not work. Is there a way to listen to this using Jquery?
$(document).ready(function () {
// console.log($('#id_customer'));
$('.modelselect2 form-control select2-hidden-accessible').on('select2:select', function (e) {
var data = e.params.data;
console.log(data);
});
});
I'll answer your question, but then give you a better solution.
First, you need to make sure the thing you are attaching .on() to actually exists. I typically use a containing DIV or failing that body or html will work.
Secondly you are missing a parameter that tells jQuery the thing you are looking to watch to be clicked on. In this case, I'm assuming it is the UL tag with the ID you provided.
This should do what you want:
$(document).ready(function () {
$('body').on("click", "#select2-id_customer-results", function() {
console.log('hello')
})
})
But a better solution would be to use the Select2 API to have it tell you when something is selected. This will be way more reliable and should make your code work after upgrades to Select2.
Something like this:
$('select[name="customer"]').on('select2:select', function (e) {
var data = e.params.data;
console.log(data);
});
NOTE: #mySelect2 is probably not what you have. Use whatever ID you used to initialize Select2 in jQuery.
You can read more about that API here: https://select2.org/programmatic-control/events
if your element is dynamically generated and you want to target that specific element. You need to specify a static container/parent element to indicate where it belongs.
Try this:
$( '#dynamicallyAddedElement' ).on( 'click', '#wrapper', function () { ... });
//where #wrapper is a static parent element in which you add the dynamic links.
So, you have a wrapper which is hard-coded into the HTML source code:
PS. Hope I helped in some way.
If you need to trigger an event when click on <li> elements, you have to use that elements id or class as the selector. Check the below code:
$(document).ready(function () {
var test = ".select2-results__option";
$(test).on("click", function() {
console.log('hello')
})
})
It turns out this is an old bug in django-auto-complete.
The code below works. I have no idea why but now I can move on.
Note: the 'name' is the value of the select2 select element (see screenshot at bottom)
document.querySelector('select[name="customer"]').onchange=function() {
console.log("myselect2name changed");
};
I have my app with tons of buttons/inputs/etc. with different events. I want to clearly identify each one of them which some event triggers on.
For example, when I have a piece of my app:
<div class="someClass">
<div>
<someOtherElement>
<div></div>
<div><button ng-click="someClickEvent($event)"></button></div>
</someOtherElement>
</div>
</div>
I want to identify somehow, which button I have just clicked:
function someClickEvent(e) {
// some identification code here
}
[edit]
Maybe I wrote this wrong... I want some identification like XPath or something that will point which button were triggered (for error logging purposes).
So when I click my button and some error occurs, I want to identify the button and log some information about it (e.g. div[0].someClass>div[0]>someOtherElement[0]>div[1]>button[0]).
You can get identify the button and log it by this:
$scope.clickFunc = function(event){
$scope.clickedElement = event.target.outerHTML;
};
DEMO: http://jsfiddle.net/rjdzuxaL/1/
Use ng-click instead on onclick
<button ng-click="myFunction($event)">test</button>
Working demo
Change HTML to:
<button ng-click="myFunction($event)">test</button> //onclick works on javascript. For Angularjs, use ng-click.
JS:
$scope.someClickEvent = function(e) {
// some identification code here
var element = e.target; // this will give you the reference to the element.
}
You should avoid handling DOM in the controller. Use directives for them.
I'm trying to simulate two click to open a menu. The first one opens the menu and the second the submenu but after the first click() the function stops.
This is my JS code:
function open_menu(id_menu, id_sub_menu) {
$('.sous-domaines a#lien-domaine-'+id_menu).click();
$('a#lien-menu-'+id_sub_menu).click();
}
I call my function in HTML with this code:
<span onClick="open_menu('0', '116')">Open sub-menu</span>
You're doing it too fast maybe.
Wrap the second one in a window.setTimeout()
can you do something like this ? set a bool after first click
var IsClick = false;
function open_menu(id_menu, id_sub_menu) {
$('.sous-domaines a#lien-domaine-'+id_menu).click();
if (IsClick){ fnSecondClick();}
}
function fnSecondClick() {
//open submenu
}
or something like this - on click check if menu is visible:
function open_menu(id_menu, id_sub_menu) {
$('.sous-domaines a#lien-domaine-'+id_menu).click();
if ($(element).is(":visible")){ fnSecondClick();}
}
Well you can give this a try, it is pretty much waht you had, other than the fact i don't have menu open somewhere
http://jsfiddle.net/tRg3e/2/
I think the .click() only works if you have a handler attached, it does not trigger the native click on the element.. I tried it without handler and the link does not go
You should stray away from 'onClick' declared in elements like that, it's bad practice if I do recall. Nonetheless, it still works.
If you could provide some HTML code it would help clarify the idea but you could set a trigger event for example:
http://jsfiddle.net/wrN2u/3/
EDIT: With a toggle - http://jsfiddle.net/wrN2u/18/
I am dynamically creating a hyperlink in the c# code behind file of ASP.NET. I need to call a JavaScript function on client click. how do i accomplish this?
Neater still, instead of the typical href="#" or href="javascript:void" or href="whatever", I think this makes much more sense:
var el = document.getElementById('foo');
el.onclick = showFoo;
function showFoo() {
alert('I am foo!');
return false;
}
Show me some foo
If Javascript fails, there is some feedback. Furthermore, erratic behavior (page jumping in the case of href="#", visiting the same page in the case of href="") is eliminated.
The simplest answer of all is...
My link
Or to answer the question of calling a javascript function:
<script type="text/javascript">
function myFunction(myMessage) {
alert(myMessage);
}
</script>
My link
With the onclick parameter...
<a href='http://www.google.com' onclick='myJavaScriptFunction();'>mylink</a>
The JQuery answer. Since JavaScript was invented in order to develop JQuery, I am giving you an example in JQuery doing this:
<div class="menu">
Example
Foobar.com
</div>
<script>
jQuery( 'div.menu a' )
.click(function() {
do_the_click( this.href );
return false;
});
// play the funky music white boy
function do_the_click( url )
{
alert( url );
}
</script>
I prefer using the onclick method rather than the href for javascript hyperlinks. And always use alerts to determine what value do you have.
<a href='#' onclick='jsFunction();alert('it works!');'>Link</a>
It could be also used on input tags eg.
<input type='button' value='Submit' onclick='jsFunction();alert('it works!');'>
Ideally I would avoid generating links in you code behind altogether as your code will need recompiling every time you want to make a change to the 'markup' of each of those links. If you have to do it I would not embed your javascript 'calls' inside your HTML, it's a bad practice altogether, your markup should describe your document not what it does, thats the job of your javascript.
Use an approach where you have a specific id for each element (or class if its common functionality) and then use Progressive Enhancement to add the event handler(s), something like:
[c# example only probably not the way you're writing out your js]
Response.Write("My Link");
[Javascript]
document.getElementById('uxAncMyLink').onclick = function(e){
// do some stuff here
return false;
}
That way your code won't break for users with JS disabled and it will have a clear seperation of concerns.
Hope that is of use.
Use the onclick HTML attribute.
The onclick event handler captures a
click event from the users’ mouse
button on the element to which the
onclick attribute is applied. This
action usually results in a call to a
script method such as a JavaScript
function [...]
I would generally recommend using element.attachEvent (IE) or element.addEventListener (other browsers) over setting the onclick event directly as the latter will replace any existing event handlers for that element.
attachEvent / addEventListening allow multiple event handlers to be created.
If you do not wait for the page to be loaded you will not be able to select the element by id. This solution should work for anyone having trouble getting the code to execute
<script type="text/javascript">
window.onload = function() {
document.getElementById("delete").onclick = function() {myFunction()};
function myFunction() {
//your code goes here
alert('Alert message here');
}
};
</script>
<a href='#' id='delete'>Delete Document</a>