For example I have long list of buttons: <input type=button name=clickbutton onclick='dosomething(this)'>
But instead of putting call to the same function in every button it would be more rational to add a single listening event that would wait for click of that button with this name. But again, there are many this buttons so I need pass clicked object to a function. For example this function must update a textarea field that is adjacent (nextSibling) to this button.
You could use jQuery:
$('input[name|="clickbutton"]').click(function() {
var currentButton = $(this);
alert(currentButton.attr('id'));
});
This attaches a click function to all input elements with a name of 'clickbutton'. currentButton is the input element that was just clicked. The function then alerts the id of the currentButton.
UPDATE: I've created a working example for you here: http://jsfiddle.net/Damien_at_SF/cdsWk/1/
Hope that helps :)
Look up event delegation. This may be what you need. There are many good resources for it on google.
Update:
Sorry, I could have put a little more effort into the answer, Here are some results Google Search...
You would then use a switch to determine what action you want to take based on the event.name attribute. Cool thing about that approach is if you have a great deal of elements on the page with events, it sounds like you do, it should make your page feel more responsive; as the browser does not have to deal with the extra overhead of on event per element.
var buttons = document.getElementsByName('clickbutton');
for (var i = 0; i < buttons.length; i++)
buttons[i].onclick = function(){
this.nextSibling.innerHTML = 'clicked!';
}
Related
So I am writing a script that can be run on a page but I want to click on this element, unfortunately, it does not have an id to get and I am trying to use the .click() function on it, but it doesn't work, here's what I have, anyone know how to fix it? This is the only element in the class also
var classes = document.getElementsByClassName('rateRecipe btns-one-small');
var Rate = classes[0];
Rate.click();
I'd suggest:
document.querySelector('.rateRecipe.btns-one-small').click();
The above code assumes that the given element has both of those classes; otherwise, if the space is meant to imply an ancestor-descendant relationship:
document.querySelector('.rateRecipe .btns-one-small').click();
The method getElementsByClassName() takes a single class-name (rather than document.querySelector()/document.querySelectorAll(), which take a CSS selector), and you passed two (presumably class-names) to the method.
References:
document.getElementsByClassName().
document.querySelector().
If you want to click on all elements selected by some class, you can use this example (used on last.fm on the Loved tracks page to Unlove all).
var divs = document.querySelectorAll('.love-button.love-button--loved');
for (i = 0; i < divs.length; ++i) {
divs[i].click();
};
With ES6 and Babel (cannot be run in the browser console directly)
[...document.querySelectorAll('.love-button.love-button--loved')]
.forEach(div => { div.click(); })
for exactly what you want (if you know the index of button):
var rate = document.getElementsByClassName('rateRecipe btns-one-small')[0];
rate.click();
or for direct action
document.getElementsByClassName('rateRecipe btns-one-small')[0].click();
with jQuery
$('.rateRecipe .btns-one-small').click(function(){
var vIndex = $('.rateRecipe .btns-one-small').index(this);
//vIndex is the index of buttons out of multiple
//do whatever
//alert($(this).val());//for value
});
class of my button is "input-addon btn btn-default fileinput-exists"
below code helped me
document.querySelector('.input-addon.btn.btn-default.fileinput-exists').click();
but I want to click second button, I have two buttons in my screen so I used querySelectorAll
var elem = document.querySelectorAll('.input-addon.btn.btn-default.fileinput-exists');
elem[1].click();
here elem[1] is the second button object that I want to click.
I have li blocks which onclick will change class ID as follows:
onclick = "document.getElementById('procblock1').id = 'procblock1Clicked';"
"document.getElementById('procblock2Clicked').id = 'procblock2';"
"document.getElementById('procblock3Clicked').id = 'procblock3';"
"document.getElementById('procblock4Clicked').id = 'procblock4';"
The line document.getElementById('procblock2Clicked').id = 'procblock2'; should revert any clicked elements (blocks) back to their original ID names.
The code works for changing the original id to the clicked id but doesn't have any effect in reverting previously clicked to the original as per lines 2,3 & 4.
I have searched hard for similar questions but can find nothing that covers this specific issue.
#Matthias - I acted upon your advice and came up with a very simplified jquery solution :
`$(function() {
$(".showinfo").click(function() { //using class instead of ID
$(".showinfo").removeClass("clicked"); //Remove all existing clicks
$(this).addClass("clicked"); //add the class to the clicked element });
});`
Posted solution in case anyone else has same query. Your help was appreciated.
If this really is part of the code you're using lines 2-4 won't work; onclick will only handle the first line. You should wrap it as a function to be called onclick, like onclick = "doStuff()" and add a function doStuff () {/* your code here */}. But that's just guessing as you only provide some part of the code in question.
In addition would be good to know what you want to achieve - in case you want to mark clicked elements, it would be a cleaner approach to add a class, e.g. "clicked" or "active", that you simply remove later on instead of changing ids.
Okay so, I want to make an OnClick function in JavaScript that makes it so when a user clicks on it, it will change the word. Is there a replaceword() function or something that which will let me do so? I know this is not real code, but for example:
<p>Quickly <span onclick="replaceword('Surf');">Search</span> The Web!</p>
If there is, then can someone tell me also how to reverse the code maybe? So when they click on it the second time, it will change back to "Search"?
If you want to jump between multiple words, you'll need to store them someplace. You could have two words in the sentence, and toggle the visibility of one or the other (which doesn't scale well), or you could even store them as values on an attribute placed on the element itself.
<p>Hello, <span data-values="World,People,Stack Overflow">World</span>.</p>
I have placed all possible values within the data-values attribute. Each distinct value is separated from the other values by a comma. We'll use this for creating an array of values next:
// Leverage event-delegation via bubbling
document.addEventListener( "click", function toggleWords ( event ) {
// A few variables to help us track important values/references
var target = event.target, values = [], placed;
// If the clicked element has multiple values
if ( target.hasAttribute( "data-values" ) ) {
// Split those values out into an array
values = target.getAttribute( "data-values" ).split( "," );
// Find the location of its current value in the array
// IE9+ (Older versions supported by polyfill: http://goo.gl/uZslmo)
placed = values.indexOf( target.textContent );
// Set its text to be the next value in the array
target.textContent = values[ ++placed % values.length ];
}
});
The results:
The above listens for clicks on the document. There are numerous reasons why this is a good option:
You don't need to wait for the document to finish loading to run this code
This code will work for any elements added asynchronously later in the page life
Rather than setting up one handler for each element, we have one handler for all.
There are some caveats; you may run into a case where the click is prevented from propagating up past a particular parent element. In that case, you would want to add the eventListener closer to your target region, so the likeliness that bubbling will be prevented is less.
There are other benefits to this code as well:
Logic is separated from markup
Scale to any number of values without adjusting your JavaScript
A demo is available for your review online: http://jsfiddle.net/7N5K5/2/
No, there isn't any native function, but you can create on your own.
function replaceword(that, word, oword) {
that.textContent = that.textContent == oword ? word : oword;
}
You can call it like this:
<p>Quickly<span onclick="replaceword(this,'Surf','Search');">Search</span>The Web!</p>
Live Demo: http://jsfiddle.net/t6bvA/6
<p id="abc">Hello</p>
<input type="submit" name="Change" onclick="change()">
function change(){
var ab=document.getElementById('abc').value;
ab.innerHTML="Hi, Bye";
}
I think so this should help you, you should go to site such as w3schools.com, its basic and it will answer your doubt
You can try something like this if you wanna use jQuery
http://jsfiddle.net/R3Ume/2/
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<body>
<p>Hello <a id='name'>John<a></p>
<input id="clickMe" type="button" value="replace" onclick="onClick();" />
<script>
function onClick() {
$('#name').text('world');
}
</script>
I'm not sure how to ask this question correct since my understanding of the DOM is lacking.
What I'm trying to do is to catch any click event on any given DOM element. I then want to save the element type as well as the complete reference to element in a Database. But I'm not sure this is at all possible?
What i want to achieve is to save a hole interaction with a web app, in a way so you can later replay every action performed on the site, in a given session.
I have tried different approaches like getting the X and Y position of the clicked element, and later on trigger a click on those x-y coordinates, but theres several problems with this approach. I've also tried to traverse the Dom backwards until i reach the body tag, to build a unike selecter, but this also have it's shortcomings.. The best solution i can think of would be to save what ever $(this) contains.
If click events are the only thing you want to track, you probably want to add click event handlers to every clickable element on the page.
This would require starting at the <body> and walking the DOM, adding handlers as you go.
At the same time, I'd add a new data-xpath attribute to each element containing an XPath selector so you can use it in your handler to note the element being clicked, and so replay the user's interaction.
See http://www.w3schools.com/xpath/xpath_intro.asp for an introduction to XPath.
Faling a sleep yesterday i got an idea and ended up with this code today. - It works as intended but I'm guessing that Xpath would perform better!?
$(document).click(function(event) {
var target = $(event.target);
var parents = target.parents();
var myParents = '';
$($(parents).get().reverse()).each(function(key, value){
var parentIndex = $(this).index()+1;
myParents += $(this).prop("tagName")+':NTH-CHILD('+parentIndex+') > ';
});
var childIndex = target.index()+1;
var childTag = target.get(0).tagName;
myParents += childTag+':NTH-CHILD('+childIndex+')';
alert(myParents);
});
The above code will return a unique selector-string likes this:
HTML:NTH-CHILD(1) > BODY:NTH-CHILD(2) > SECTION:NTH-CHILD(1) > UL:NTH-CHILD(1) > LI:NTH-CHILD(3) > A:NTH-CHILD(1)
Here's some low-hanging fruit for those more comfortable with Javascript than I...
I want to improve a Moodle plugin's admin UI. (Moodle is a PHP-based web app). What I need to do is take what is currently a text box, with semi-colon delimited entries and replace that with a editable list.
The HTML elements I would use is a select list, a text input field and another hidden textfield. I guess a couple of submit buttons too, one for adding, and the other for removing of entries.
The behaviour would be:
Entries can be added to the select list from the visible textbox upon some kind of submit (this cannot reload the page).
The hidden textbox would contain all the entries from the select list, just semi-colon delimited
There's a function to remove entries from the select list that also does not reload the page.
The hidden textbox is updated with add/remove actions
This seems to me like something that's easy enough. Though I'm having a hard time finding a close enough example to rip off.
This sample code is as close as I've found thus far. There's got to be some good examples of precisely this sort of thing out there. Any decent pointers will be rewarded with + votes.
What you want to do is use JavaScript and manipulate with the DOM of the webpage. Basically, the HTML of a webpage is parsed and rendered by the browser into a tree of elements. Each HTML tag like <select> is an element in the tree. You use JavaScript to interact with this tree by performing operations like removing elements from this tree or adding elements to this tree. (Note that preforming operations on the tree will not refresh the page.)
The standardized API to do these sorts of manipulation in JavaScript is known as the DOM. However, many people, myself included, think that this API is very clunky and not nearly expressive enough. Doing even trivial things require tons of lines of code. For this reason, many developers do not use the DOM directly instead using more powerful libraries, such as jQuery, to make their lives easier.
Below is an example of some HTML + JavaScript that I think mimics most of your requirements. Ideally for learning purposes, this would be written purely using the standard W3C DOM API, but since your problem is not that trivial, I resorted to using jQuery instead.
The HTML:
<select id="list" multiple="multiple"></select>
<input id="removeButton" type="button" value="Remove"></input>
<div>
<input id="optionAdder" type="text"></input>
<input id="addButton" type="button" value="Add"></input>
</div>
<br>
<input id="clearButton" type="button" value="Clear All"></input>
<div>Not So Hidden: <input id="hidden" type="text"></input></div>
The JavaScript:
// Uses jQuery to define an on document ready call back function
$(function(){
// The code in this function runs when the page is loaded
var options = []; // contains all the options
// add new option to drop-down
var addOption = function(optText) {
// Create new option element and add it to the <select> tag
$('<option></option>')
.attr('value', optText).text(optText)
.appendTo( $('#list') );
};
// writes the names of all the options in the "hidden" text box
var fillHidden = function() {
$('#hidden').val('');
var hiddenText = "";
for(var i=0; i< options.length; i++) {
if(hiddenText) {
hiddenText += "; ";
}
hiddenText += options[i];
}
$('#hidden').val(hiddenText);
}
// Bind the click event of the "Add" button to add an option on click
$('#addButton')
.click(function(){
var optText = $('#optionAdder').val();
if(optText) {
addOption(optText);
}
$('#optionAdder').val('');
options.push(optText);
fillHidden();
});
// Bind the click event of the "Remove" button to remove the selected options on click
$('#removeButton')
.click(function(){
$('#list option:selected').each(function(){
var optIndex = $.inArray($(this).val(), options);
if(optIndex > -1) {
options.splice(optIndex, 1);
$(this).remove();
}
fillHidden();
});
});
// Bind the click event of the "Clear" button to clear all options on click
$('#clearButton')
.click(function(){
$('#list').children().remove();
options = [];
fillHidden();
});
});
Here is a jsfiddle demonstrating the code