Clicking a button/href with JavaScript/Jquery by class name - javascript

I'm trying to click a button that brings up an edit screen on the same page.
Eg. Click "edit user", edit screen pops up on the same page without redirecting, change name, save. This button does not redirect to a new page.
The code for this button is the following:
<i class="fa fa-pencil"></i> Edit
For some reason I can click every other button on this website that's in the same exact form but I can't click this one. There are no IDs at all so calling by the class name is the only other method I know.
This is what I've tried:
setTimeout(function() {
document.getElementsByClassName(" btn btn-xs btn-inverse btn-modify")[0].click();
}, 3000);
I tried using some Jquery instead as well but no luck. Am I doing something wrong or is this all that I can really do? The other buttons I clicked either redirected me to a different site or just brought up some information on the same screen.
Thanks in advance.
Edit:
It seems that when I try iterating through the different buttons, who all have similar starting class names, I can iterate and click every button except for the edit button. So it's safe to assume that this isn't an issue with the code, so thank you everyone for the help and suggestions.
Edit #2:
Here is the code for all three buttons:
<div class="btn-group"><i class="stm stm-goog"></i> &nbsp
<i class="fa fa-pencil"></i> Edit
<i class="fa fa-bar-chart"></i><button type="submit" class="btn btn-xs btn-danger btn-submit"><i class="fa fa-trash-o"></i></button></div>

When searching for elements by class, it's better to use:
document.querySelector(); // Finds first matching element only
and
document.querySelectorAll(); // Finds all matching elements
instead of document.getElementsByClassName() as this returns a "live node list" and hinder performance.
When searching for classes with these methods, remember to include the dot (.) to signify classes and when multiple classes are used, do not include spaces. The spaces are only used when setting multiple classes.
Also, if there is only one class that is unique to the element you wish to find, you only need to search on that one class.
Lastly, only use a elements for navigation. If you simply need something to click, just about any object can have a click event handler.
var edit = document.querySelector(".btn-modify");
edit.addEventListener("click", function(){ console.log("clicked")});
setTimeout(function() {
edit.click();
}, 3000);
// Addtional test
var edit = document.querySelectorAll(".btn.btn-xs.btn-inverse")[1];
edit.addEventListener("mouseover", function(){
console.log("moused over");
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="btn-group">
<a href="https://google.com" target="_blank" class="btn btn-xs btn-inverse">
<i class="stm stm-goog">X</i> <!-- <-- You missed a semi-colon here. -->
</a>
<a href="#" data-id="29508"
class="btn btn-xs btn-inverse btn-modify">
<i class="fa fa-pencil"></i> Edit
</a>
<a href="#" data-page-modal="https://*randomwebsite*.com/manage/stats/301&q=11"
class="btn btn-xs btn-inverse">
<i class="fa fa-bar-chart">X</i>
</a>
<button type="button" class="btn btn-xs btn-danger btn-submit"><i class="fa fa-trash-o"></i>TEST</button></div>

Because you are trying to select the element by its class you need to loop through the elements.
So if you wanna use jQuery you would do like so:
$(".btn-modify").each(function(){
$(this).click(function(){
your code here
});
});

If you want to fetch the element having all the class, try this:
JQuery
$(".btn.btn-xs.btn-inverse.btn-modify")
Plain JavaScript
document.querySelectorAll(".btn.btn-xs.btn-inverse.btn-modify")
Giving a space in between a class names in a css like selector meant that (next one) is a nested element in any depth. use . to indicate its a class, and write them together (without a space) you are searching for elements having all the lasses. And getElementsByClassName is not a css like selector, its can take only a class name and all those element having that class.

Related

Change aria-expanded="true" to false on page load

This is the button that triggers the side menu open / close on Moodle boost theme. I am trying to keep the menu hidden by default on page load.
So, I need to set <button aria-expanded="true" to <button aria-expanded="false" on page load. However, all the Javascript snippets I have tried need the element to have an 'Id' or a 'Name'; and this button has neither.
Question : How to I change the <button aria-expanded="true" to <button aria-expanded="false" on page load - without changing the source code of Moodle ?
<button aria-expanded="true"
aria-controls="nav-drawer"
type="button"
class="btn nav-link float-sm-left mr-1 btn-secondary"
data-action="toggle-drawer"
data-side="left"
data-preference="drawer-open-nav">
<i class="icon fa fa-bars fa-fw "
aria-hidden="true" aria-label="">
</i>
<span class="sr-only">Side panel</span>
</button>
Tried so far : I have searched if someone has done this already. Could not find anything. Tried several onload Javascript snippets, but nothing worked. Will appreciate some guidance & help.
You can look for the icon or a more specific element since the icon can be used more than once (or select it with :nth-child) and look up the previous element with jQuery. Then change the attribute of the button accordingly.
$('.icon fa fa-bars fa-fw').prev().attr("aria-expanded","false");
Below is the link to my codepen solution written in pure javascript and here is the explanation:
var btn = document.querySelectorAll("button"), dropdownBtn;
window.onload = function(){
for (var i=0; i<btn.length; i++) {
if(btn[i].getAttribute("data-action") == "toggle-drawer") {
console.log(btn[i]);
btn[i].setAttribute("aria-expanded", "false");
break;
}
}
};
Since you don't have any unique class or id o your button so went ahead and assumed that any one of the data-attribute on your button is unique (in this case data-action). Also, I assumed that your HTML document has many buttons hence I selected all the buttons and then iterated all over them to find the data-action attribute and as soon as I found it I set its aria-expanded value to false and exited the loop.
And all these happened while the document is loading.

How to toggle one of many links with icons using JavaScript

I have several dynamically created links which rendered as buttons and the buttons texts are replaced with icons. I need to toggle one of the link button icons when clicked. The method that I am using is not working out. See code below: I do not want to use JQuery at this time unless it’s within a function.
<a class="button" onclick="command('removeFormat');" title="Remove Format"><i class="fas fa-eraser"></i></a>
<a class="button" onclick="command('fullScreen');" title="Full Screen"><i class="fas fa-expand"></i></a>
<a class="button" onclick="doToggleView();" title="Source"><i class="fa fa-code"></i></a>
<a class="button" onclick="submitForm();" title="Save"><i class="far fa-save"></i></a>
//JS
function command(cmd){
if(cmd == 'fullScreen'){
$(".fa-expand").toggleClass('fa-expand fa-compress');
}else{
$(".fa-compress").toggleClass('fa-compress fa-expand');
}
}
I also try using the following codes:
$("i").toggleClass('fa-compress fa-expand');
$("a .button").find("i").toggleClass('fa-expand fa-compress');
This is the fix to resolve the issue.
function command(cmd){
$('i.fas').toggleClass('fa-expand fa-compress');
}

JavaScript (jQuery) does not react anymore after I have changed the element [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 4 years ago.
I have 2 links:
<span id="a-start-container">
<a id="a-start" href="#">
<i class="fa fa-fw fa-play inner-circle-color"></i>
</a>
</span>
<span id="a-stop-container">
<a id="a-stop" href="#">
<i class="fa fa-fw fa-play inner-circle-color"></i>
</a>
</span>
When I click on the first one (a-start) I'm disabling it by removing the <a> element and at the same time I enable the second one (a-stop) by adding the <a> element:
$(document).ready(function() {
$("#a-start").click(function(e){
$("#a-stop-container").html("<a id='a-stop' href=''><i class='fa fa-fw fa-stop inner-circle-color'></a>");
$("#a-start-container").html("<i class='fa fa-fw fa-play inner-circle-color'>");
})
});
When I click on the second one (a-stop) I'm disabling it by removing the <a> element and at the same time I enable the first one (a-start) by adding the <a> element:
$(document).ready(function() {
$("#a-stop").click(function(e){
$("#a-start-container").html("<a id='a-start' href=''><i class='fa fa-fw fa-play inner-circle-color'></a>");
$("#a-stop-container").html("<i class='fa fa-fw fa-stop inner-circle-color-off'>");
})
});
The problem is that it works only for the first click. For example I click on the first one (a-start), then it changes a-start and enables a-stop. But then, when I click on a-stop, JavaScript does not react anymore. The same situation the other way round. Both work fine until the <a> element gets changed - then I have to reload the page to get it run again.
There is no information in the console.
What am I doing wrong?
you should consider changing it to on instead of click based on the pattern that you are using. Usage of on can be found her: http://api.jquery.com/on/
What you are doing is replacing entire DOM content on which handler/listener is registered and thus it dont get re-registered on DOM change which is happening after first click event.
However what seemed like you only wanted to toggle class-name and text of the link which should have been handled via http://api.jquery.com/toggleClass/ which would be more appropriate.

Click button(s) copy to clipboard using jQuery

I've a situation where a user need to copy (click copy-to-clipboard icon) a link, however I've multiple dynamic links on a single page.
I've found the solution on the following post but I don't know a way to pass clicked icon ID to function as parameter and get the link copied to clipboard.
Click button copy to clipboard using jQuery
<i class="fa fa-link pull-right" id"copyToClipboard1"></i>
<i class="fa fa-link pull-right" id"copyToClipboard2"></i>
<i class="fa fa-link pull-right" id"copyToClipboard3"></i>
I went through the following post here in order to pass element ids to the function but no use as I just started crawling on jQuery path.
jQuery passing element ID into jquery statement?
Thanks in advance.
I don't have enough rep point therefore posting a new question [duplicate].

Insert <a> Into a div generated by a plugin with javascript or jQuery

I am working with a plugin that provides IDX data for listings on a WordPress website. The plugin uses jQuery to query a database for information that it displays on the page. The plugin is not very customizable past simple styling and I would like to insert a link to save to favorites
The link for saving to favorites can be found by viewing this page:
http://angelandpatty.com/homes-for-sale-details/8635-La-Entrada-Avenue-Whittier-CA-90605/PW14217291/306/
All the property details pages have the "save to favorites" button at the top of the page. This is what I found with the inspector:
<a data-toggle="modal" data-target="#ihfsaveListing" class="btn btn-primary btn-detail-leadcapture save-listing-btn"> <span class="hidden-xs"> <i class="glyphicon glyphicon-heart fs-12"></i> Save To Favorites </span> <span class="visible-xs fs-12"> Save To<br>Favorites </span> </a>
I am assuming the data-target is what is causing the button to take action.
What I would like to do is find a way to insert this same button, perhaps with a different icon like a thumbs up or a star, into the property stubs.
The property stubs are viewable on pages like this:
http://angelandpatty.com/homes-for-sale-in-friendly-hills/
I would like to find a way to insert this possibly after #ihf-main-container .col-xs-9
If there is any way to do this with Javascript or with jQuery I sure would like to know.
Thank you for all of your assistance. I tried searching for some situation like this but was unlucky
Are you looking for the following answer?
var button = $('<a data-toggle="modal" data-target="#ihfsaveListing" class="btn btn-primary btn-detail-leadcapture save-listing-btn"> <span class="hidden-xs"> <i class="glyphicon glyphicon-heart fs-12"></i> Save To Favorites </span> <span class="visible-xs fs-12"> Save To<br>Favorites </span> </a>');
$('#ihf-main-container .col-xs-9:first').after(button);
See: http://api.jquery.com/after/
.after(content [, content ] )
Description: Insert content, specified by the parameter, after each element in the set of matched elements.
You may need to initialize the button as required.

Categories