How to trigger button with html href? - javascript

I have the following code in my HTML/CSS/Div table, and the href works without issue. Is it possible to replace the href code such that when this image is clicked, instead of opening the URL, a button click is activated?
Working Code
<a class="test-link" href="https://www.example.com" target="_blank" rel="noopener">
<img class="testgrey" src="./grey.svg" />
<img class="test-white" src="./white.svg" />
</a>
Desired Outcome from clicking on the image defined above:
this button gets activated without actually placing the button on the html page:
<a class="button button--small card-figcaption-button quickview" tabindex="0" data-product-id="113">Buy</a>

You can add a click handler to your anchor that delegates a click event to the button.
// Delagate the link click to the button click
document.querySelector('#my-link').addEventListener('click', e =>
document.querySelector('#my-button').click());
// Handle button clicks
document.querySelector('#my-button').addEventListener('click', e =>
console.log('button click...'));
<a id="my-link" href="#">Click Me</a><br><br>
<button id="my-button">I will be clicked programatically</button>

You can attach an event listener directly to the <a> element and call the button handler;
document.querySelector('.test-link').addEventListener('click', function(event){
//prevent navigation
event.preventDefault();
event.stopPropagation();
// call your button handler directly
callButtonEventHandler();
return false;
});
You can't trigger a button click without a button on the page.
You can only call it's handler if it's available in javascript.

Related

jQuery cannot trigger button click from another button click

My goal is to replace a button with another button, but I am running into some issues. I am able to trigger the first button click and I am able to cause an alert with the second button click, but for some reason when I try to trigger the first button click in the click event handler of the second button, it doesn't work. What am I doing wrong? For some context, I'm doing this in Powerapps Portals by adding a Content Snippet.
$(window).load(function() {
//Code to Add Custom 'Register' Button (and Hide the original one- currently commented out)
$('#SubmitButton').after('<input type="submit" name="ctl00$ctl00$ContentContainer$MainContent$MainContent$mySubmitButton" value="Register" id="mySubmitButton" class="btn btn-primary">');
//$('#SubmitButton').hide(); *THIS WORKS*
//$("#SubmitButton").click(); *THIS ALSO WORKS*
$("#mySubmitButton").click(function()
{
//window.alert('yes!'); *THIS WORKS*
$("#SubmitButton").click(); // *THIS DOES NOT WORK*
});
});
You need to prevent the default action to stop the form from submitting when the button is clicked.
$("#mySubmitButton").click(function(e){
e.preventDefault();
$("#SubmitButton").click();
});
Alternatively, you can set the button's type to "button" so clicking it does not submit the form by default.
$('#SubmitButton').after('<input type="button" name="ctl00$ctl00$ContentContainer$MainContent$MainContent$mySubmitButton" value="Register" id="mySubmitButton" class="btn btn-primary">');

Bootstrap popover hide on outside click. Opens only on second click

Used solutions from other answers to hide Bootstrap popover on outside click.
However it then requires two clicks to open the popover again (if I closed it by clicking outside).
It works alright and opens on first click when I use the button to close it.
Here is problem recreated: http://codepen.io/olegovk/pen/BjQmQe
The html used:
<!-- Popup button -->
<a id="menu-button" class="menu-button" data-html="true" role="button" data-container="body" data-toggle="popover" data-placement="bottom">Menu</a>
<!-- Popup content -->
<div id="menu-content">
<h1>Hello</h1>
<p>Good bye</p>
Link
</div>
And the jQuery:
$('#menu-button').popover({
content: $('#menu-content').html(),
html: true
});
$('html').on('click', function(e) {
if (typeof $(e.target).data('original-title') == 'undefined' &&
!$(e.target).parents().is('.popover.in')) {
$('[data-original-title]').popover('hide');
}
});
Any ideas why it happens and how to make popup always open on first click?
One note: I find it impossible to use this "official" solution because it makes it impossible to click on links inside popup: http://getbootstrap.com/javascript/#dismiss-on-next-click
You don't need extra Js to close the popover, as the documentation says docs
Dismiss on next click
Use the focus trigger to dismiss popovers on the next click that the user makes.
<a tabindex="0"
class="btn btn-lg btn-danger"
role="button" data-toggle="popover"
data-trigger="focus" title="Dismissible popover"
data-content="And here's some amazing content. It's very engaging. Right?">Dismissible popover
</a>
data-trigger="focus" close the popover on the next click of the users.
In many cases (mostly the rest of the code in your document) once you leave the popover, you have to regain focus on it. This event is not easily binding the click event to the html or body. Buttons tend to regain the focus much better than hyperlinks. (This is my theory, I'd question it, but it's what I've read here and there) The point is, this code works lol that's the important thing, isn't it?
I suggest you change the hyperlink to a button and style it to make it look as a hyperlink if you need to and use the code in the jFiddle provided here
$('[data-toggle="popover"]').popover();
$('body').on('click', function (e) {
$('[data-toggle="popover"]').each(function () {
//the 'is' for buttons that trigger popups
//the 'has' for icons within a button that triggers a popup
if (!$(this).is(e.target) && $(this).has(e.target).length === 0 &&
$('.popover').has(e.target).length === 0) {
$(this).popover('hide');
}
});
});
Here is working jfiddle

Why jquery click event is not firing on firefox?

I have this function in JS :
jQuery(function ($) {
$(document).on("click", ".botaoExcluirRecibos", function (e) {
e.preventDefault();
alert("Fired!");
});
});
And in my asp.net page i have this button:
<div class="listaExcluir" id="listaExcluir">
<ul id="listaArquivos">
<li>
<div class="voceAnexou"></div>
<div class="divInformacoesAtendimento divInformacoesAtendimentoTabelaRecibo">
<p>VocĂȘ anexou:<strong> file1.png </strong></p>
<button class="botaoVermelhoPequeno botaoExcluirRecibos" onclick="return false;">Excluir</button>
</div>
</li>
</ul>
</div>
The button is added dynamically on the li tag, and more buttons can be added by the user.
It's not firing the click event at FIREFOX , but at CHROME is.
Obs: I had to add the onclick event inline on the button for preventing the postback issue.
First, you can add "return false;" to your event handler and it will avoid postbacks - you don't need to have it inline.
Second, I would recommend a binding function:
function BindClick(){
$(".botaoExcluirRecibos").unbind("click"); // To prevent double-binding click events!
$(".botaoExcluirRecibos").on("click", function(e){
e.preventDefault();
console.log("Fired!"); //Use the console instead of alerts for debugging purposes!
return false;
});
}
Now, just call:
BindClick();
Every time you add a control to the page that will need this event handler. This should work in every browser.

How can I prevent link behavior on clicking an image inside an anchor element?

I have a code similar to this:
<a href='link.html'>goto link page <img src='images/edit.gif' alt='Dont Go, just edit' onclick='doEdit()'></a>
Now I want the href link to work as normal if you click on the text, but if you click on the image, it should do something else and not goto the link at all.
There is also a restriction, I cannot edit the link or its text, the only thing that I have total control over is the img tag and its called onclick function. So I have to prevent the link from going on from within that img tag.
Any help will be appreciated.
Just preventDefault on the click event when the target is an <img>
yourAnchor.addEventListener('click', function (e) {
if (e.target.tagName === 'IMG')
e.preventDefault();
});
Now I want the href link to work as normal if you click on the text, but if you click on the image, it should do something else and not goto the link at all.
The correct way to do that is to not put the img inside the link.
However, if you really want to do that, change your onclick to:
onclick='doEdit(event)'
...and in doEdit:
function doEdit(event) {
if (event.stopPropagation) {
event.stopPropagation(); // Standard
}
else {
event.cancelBubble = true; // Old IE
}
// ...your img logic...
}
That will prevent the click event from bubbling to the link. You need the test for stopPropagation because IE8 and earlier don't have it (or preventDefault), they use properties instead (cancelBubble = true for stopPropagation and returnValue = false for preventDefault). (We're probably stuck with IE8 at least another year, maybe more, despite XP end-of-life...)
Pass the event through to the doEvent method call, similar to this:
<a href='link.html'>goto link page <img src='images/edit.gif' alt='Dont Go, just edit' onclick='doEdit(event)'></a>
Then you can call event.preventDefault() to cancel the event and do your own thing, similar to this:
function doEdit(event){
// your code here
event.preventDefault();
}
DEMO - Using the event object to cancel the event.
Im not quite sure what you mean but if you want the text to have a link and the image to have a onclick event
text
<a href='link.html'>goto link page</a>
image
<img src='images/edit.gif' alt='Dont Go, just edit' onclick='doEdit()'></img>
My initial thought is to simply remove the image tag from between the link tags.
<a href='link.html'>goto link page</a>
<img src='images/edit.gif' alt='Dont Go, just edit' onclick='doEdit()'/>
Are there more restrictions that do not allow you to do something like this?

click event fires twice for button inside link

I'm using bootstrap to create the stacked pills nav control. Each entry in the control is a link, and that link element also contains a button. The button may be clicked to delete the list entry, or the list entry itself may be clicked to perform some action on it.
The html for each list entry looks like this:
<li>
<a href="#" id="launch_me">Some title
<button class="my-class" id="remove_me">
<i class="icon-remove"></i>
</button>
</a>
</li>
These items are added dynamically based on a response from a server. The jquery then adds the click handler via:
$("#launch_me").click((function (info) {
return function () {
launch(info);
};
})(myInfo));
$("#remove_me").click((function (info) {
return function () {
remove(info);
};
})(myInfo));
When I click on the button to delete the entry, the 'remove' click routine is triggered, followed by the launch routine.
How can I make it so clicking the remove button only results in the remove click handler being run?
Thanks!
Try this:
$("#remove_me").click((function (info) {
return function (e) {
e.stopPropagation();
remove(info);
};
})(myInfo));
http://api.jquery.com/event.stopPropagation/
This will prevent the click event of the "Remove Me" button from bubbling up to its parent "Launch Me" container and executing its click handler.
Your before: http://jsfiddle.net/HVExt/
Mine after: http://jsfiddle.net/HVExt/1/
MyInfo looks dodgy to me. I wiuld skip that and add ; instead. But then i don't know the rest of your code...

Categories