Tooltips + Highlight Animation With Clipboard.js Click - javascript

I've successfully installed clipboard.js and have gotten snippets of text to copy to the clipboard upon click. I'm going to be nesting these snippets of text (or the "btn"s they're within) in the cells of a table.
My challenge:
I need the snippets of text to give me a Tooltip "Copied!" message so that people are aware they are clickable. A great example of this is on the clipboard.js documentation page -- click on any of the buttons that cut or copy to see the tooltip message.
From clipboard.js' documentation:
Although copy/cut operations with execCommand aren't supported on
Safari yet (including mobile), it gracefully degrades because
Selection is supported.
That means you can show a tooltip saying Copied! when success event is
called and Press Ctrl+C to copy when error event is called because the
text is already selected.
I'm not particularly adept at JS (it took me a few hours to get this far). So I'm at a dead end... was able to install everything on WP, enqueue the script, and add the text/ functionality:
<!-- 1. Define some markup -->
<div id="btn" data-clipboard-text="1">
<span>text to click</span>
</div>
<!-- 2. Include library -->
<script src="/path/to/dist/clipboard.min.js"></script>
<!-- 3. Instantiate clipboard by passing a HTML element -->
<script>
var btn = document.getElementById('btn');
var clipboard = new Clipboard(btn);
clipboard.on('success', function(e) {
console.log(e);
console.info('Action:', e.action);
console.info('Text:', e.text);
console.info('Trigger:', e.trigger);
});
clipboard.on('error', function(e) {
console.log(e);
console.error('Action:', e.action);
console.error('Trigger:', e.trigger);
});
</script>
What should I add?
Thanks!

Seems like all you want to do is integrating Clipboard.js with a Tooltip solution.
So here's how you can accomplish that using Bootstrap's Tooltip.
// Tooltip
$('button').tooltip({
trigger: 'click',
placement: 'bottom'
});
function setTooltip(btn, message) {
$(btn).tooltip('hide')
.attr('data-original-title', message)
.tooltip('show');
}
function hideTooltip(btn) {
setTimeout(function() {
$(btn).tooltip('hide');
}, 1000);
}
// Clipboard
var clipboard = new Clipboard('button');
clipboard.on('success', function(e) {
setTooltip(e.trigger, 'Copied!');
hideTooltip(e.trigger);
});
clipboard.on('error', function(e) {
setTooltip(e.trigger, 'Failed!');
hideTooltip(e.trigger);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.10/clipboard.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<button class="btn btn-primary" data-clipboard-text="It worked!">Click me</button>
<button class="btn btn-primary" data-clipboard-text="It worked again!">Click me</button>

I've come up with a slight improvement to Zeno's code, which wraps it in a jQuery function, and supports copying from an arbitrary element:
if (typeof $.uf === 'undefined') {
$.uf = {};
}
$.uf.copy = function (button) {
var _this = this;
var clipboard = new ClipboardJS(button, {
text: function(trigger) {
var el = $(trigger).closest('.js-copy-container').find('.js-copy-target');
if (el.is(':input')) {
return el.val();
} else {
return el.html();
}
}
});
clipboard.on('success', function(e) {
setTooltip(e.trigger, 'Copied!');
hideTooltip(e.trigger);
});
clipboard.on('error', function(e) {
setTooltip(e.trigger, 'Failed!');
hideTooltip(e.trigger);
});
function setTooltip(btn, message) {
$(btn)
.attr('data-original-title', message)
.tooltip('show');
}
function hideTooltip(btn) {
setTimeout(function() {
$(btn).tooltip('hide')
.attr('data-original-title', "");
}, 1000);
}
// Tooltip
$(button).tooltip({
trigger: 'click'
});
};
// Link all copy buttons
$.uf.copy('.js-copy-trigger');
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.10/clipboard.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<form>
<div class="form-group">
<label>Email</label>
<div class="input-group js-copy-container">
<input type="text" class="form-control js-copy-target" name="email" autocomplete="off" value="example#example.com" placeholder="Email goes here" disabled>
<span class="input-group-btn">
<button class="btn btn-default js-copy-trigger" type="button">Copy</button>
</span>
</div>
</div>
</form>
You'll notice that we have our button with a class of js-copy-trigger, and the text/control to be copied with the js-copy-target class. Both of these are wrapped in a common js-copy-container class.
This is much better than using id targets, because you often need to generate multiple copy buttons (for example, in a table), and ids must be unique on a page.

Related

How to reference the element that was clicked in the IF statement

How to hide the p that was clicked in the code? Existing new ones?
(function($) {
$('body').on('click', function(event) {
if (event.target == $('button')[0]) {
$('body').append('<p class="myp">text</p>')
}
if ($(event.target).attr('class') == 'myp') {
// hide the clicked p
}
})
})(jQuery)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Add</button>
<p class="myp">text</p>
<p class="myp">text</p>
To make your logic work to detect the p which was clicked, use hasClass(), then hide(), like this:
(function($){
$('body').on('click', function(event) {
if (event.target == $('button')[0]) {
$('body').append('<p class="myp">text</p>')
}
if ($(event.target).hasClass('myp')) {
$(event.target).hide();
}
})
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Add</button>
<p class="myp">text</p>
<p class="myp">text</p>
However, I presume you're attempting to work with the click event on the body in this manner because the child elements are dynamically generated. As such there's a much better way of achieving what you're doing here; delegated event handlers:
jQuery(function($) {
$(document).on('click', 'button', function() {
$('body').append('<p class="myp">text</p>');
}).on('click', '.myp', function() {
$(this).hide();
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Add</button>
<p class="myp">text</p>
<p class="myp">text</p>
Why with event.target .Just target with class or id of element to initiate the function
$(document).ready(function() {
$('#add').on('click', function() {
$('body').append('<p class="myp">text</p>')
})
}).on('click', 'p.myp', function() {
$(this).hide();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add">Add</button>
<p class="myp">text</p>
<p class="myp">text</p>

Clone and Remove Method efficiently if possible

I hope that someone can help me please.
I need for the hidden text to be cloned and have the clone be removed regardless of the the status of the hidden text. Right now the Hidden text will show and when cloned, it produces the clone but the remove function does not work on the clone. Instead the remove function of the text that the duplicate was cloned from affects the clone. I would like for the Clone copy to hold the same events as the hidden text but independent of the status it was copied from.
I am trying to figure out how to use the cloning and remove methods with a table I am building. I have searched online with .data(array[1]) and .hide and .show. but in order for my idea to work I NEED to use the remove and clone if possible!
I APPRECIATE IT!
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
var count = 1;
var $clone = $(".t1").clone(true)
$(document).ready(function(){
$(".hide0").click(function(){
$(".t0").hide();
});
$(".show0").click(function(){
$(".t1 , .t0").show();
});
$(".hide1").click(function(){
$(".t1").remove();
});
$(".show1").click(function(){
if(count < 2) {
$(".t1").clone(false).appendTo("body");
count++;
}
});
});
</script>
</head>
<body>
<div class="t0">Original Text. <br /></div>
<button class="show0">Add Project</button>
<br />
<div class="t1" style="color:red; display:none;">
Hidden Text when removed, clone copy is removed and cannot be regenerated. Clone copy should hold the same events as the original but independent of the status it was copied from. <br>
<button class="show1">Add Project</button>
<button class="hide1">Remove Project</button><br /></div>
<div class="t2" style="color:blue; display:none;">
If you click on the "Hide" button, I will disappear.<br>
<button class="hide2">Remove Project</button><br /></div>
</body>
</html>
I believe your problem is how to handle events for dynamically created elements (in this case button add and remove in t1 class).
Code
$(document).on("click", ".show1", function(e) {
if ($(".t1").length < MaxRows) {
addRows();
}
});
$(document).on("click", ".hide1", function(e) {
$(this).parent(".t1").remove();
});
And the second problem is cloning elements. It will be easier if you do the following:
create a div named original
clone this original
change original class name to t1
append it to a row or container class to hold your clones
Code
function addRows() {
$(".t1-original")
.clone(false)
.removeClass("t1-original")
.addClass("t1")
.appendTo(".data-rows")
.show()
.find(".name").html(new Date().toISOString() + " <br/>");
}
var MaxRows = 3;
function addRows() {
$(".t1-original")
.clone(false)
.removeClass("t1-original")
.addClass("t1")
.appendTo(".data-rows")
.show()
.find(".name").html(new Date().toISOString() + " <br/>");
}
$(document).ready(function() {
$(".show0").click(function() {
// $(".t1 , .t0").show();
if ($(".t1").length < MaxRows) {
addRows();
}
});
// .hide0 class does not exist?
$(".hide0").click(function() {
$(".t0").hide();
});
$(document).on("click", ".show1", function(e) {
if ($(".t1").length < MaxRows) {
addRows();
}
});
$(document).on("click", ".hide1", function(e) {
$(this).parent(".t1").remove();
});
// $(".hide1").click(function() {
// $(".t1").remove();
// });
//$(".show1").click(function() {
// if (count < 3) {
// $(".t1").clone(false).appendTo("body");
//
// count++;
// }
//});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="t0">
Original Text.
<br />
</div>
<button class="show0">Add Project</button>
<br />
<div class="t1-original" style="color:red; display:none;">
<span class="name"></span> Hidden Text when removed, clone copy is removed and cannot be regenerated. Clone copy should hold the same events as the original but independent of the status it was copied from.
<br>
<button class="show1">Add Project</button>
<button class="hide1">Remove Project</button>
<br />
</div>
<div class="data-rows">
</div>
<div class="t2" style="color:blue; display:none;">
If you click on the "Hide" button, I will disappear.
<br>
<button class="hide2">Remove Project</button>
<br />
</div>

disable click on div element

I've been trying for a good while to try and disable a click on a div.
The reason behind this is to stop unauthorised users from triggering events etc which are activated when a user clicks on a div. From my attempt below i tried a click false but it doesnt seem to work, maybe im not using the correct syntax to disable the div?
$('#content2').on('click', false);
update:
here is the complete code involved
View
<h2>Notifications & Updates</h2>
<p id="content2" contenteditable"true" ></p>
<button id="save">Save Changes</button>
</div>
<div id="Section2"></div>
#*Scripts go at end for the contenteditable div to load correctly*#
<script type="text/javascript" src="~/Scripts/jquery.js"></script>
<script type="text/javascript" src="~/Scripts/editable.js"></script>
<script type="text/javascript" src="~/Scripts/EditContentHome.js"></script>
#if (User.Identity.Name == "WORKER")
{
<script type="text/javascript" src="~/Scripts/SecurityEditHide.js"></script>
}
SecurityEditHide.JS
window.onload = function () {
$('textarea').prop('disabled', true);
$('#content2').on('click', false);
$('#content2').prop('contenteditable', false);
$('#save').hide();
};
EditContentHome.JS
$("#content2").click(function () {
$("#save").show(1000);
});
$("#save").click(function () {
$("#save").hide(1000);
});
Change
$('#content2').on('click', false);
to
$('#content2').off('click');
That removes the click handler that you've set up in your earlier script. (Example below.)
Your $('#content2').on('click', false); didn't work because all it did was attach a second handler to the element that prevented the default action and stopped propagation. But those don't do anything to prevent other handlers for the same element getting called. (There is stopImmediatePropagation, which does, but you're really better off just removing the handler entirely in this case.)
Live example:
<h2>Notifications & Updates</h2>
<p id="content2" contenteditable="true">Presumably some text here</p>
<button id="save">Save Changes</button>
</div>
<div id="Section2"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
// From EditContentHome.JS:
$("#content2").click(function () {
$("#save").show(1000);
});
</script>
<script>
// From SecurityEditHide.JS:
window.onload = function () {
$('textarea').prop('disabled', true);
$('#content2').off('click'); // <==== Change is here
$('#content2').prop('contenteditable', false);
$('#save').hide();
};
</script>
Naturally divs are not clickable except you attach an onclick event to them , however you can do this
.enable{
//indicate your preferred color
background-color: blue;
cursor : pointer ;
}
.disable{
background-color: grey;
cursor:none ;
}
You can then check for user authorization when a click is done if authorized apply the right css using jquery.removeClass().addClass('enable') else jquery.removeClass().addClass('disable').

Bootstrap Alert Auto Close

My need is to call alert when I click on Add to Wishlist button and should disappear the alert in 2 secs. This is how I tried, but the alert is disappearing instantly as soon as it is appearing. Not sure, where the bug is.. Can anyone help me out?
JS Script
$(document).ready (function(){
$("#success-alert").hide();
$("#myWish").click(function showAlert() {
$("#success-alert").alert();
window.setTimeout(function () {
$("#success-alert").alert('close');
}, 2000);
});
});
HTML Code:
<div class="product-options">
<a id="myWish" href="" class="btn btn-mini">Add to Wishlist </a>
Purchase
</div>
Alert Box:
<div class="alert alert-success" id="success-alert">
<button type="button" class="close" data-dismiss="alert">x</button>
<strong>Success!</strong>
Product have added to your wishlist.
</div>
For a smooth slide-up:-
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").slideUp(500);
});
$(document).ready(function() {
$("#success-alert").hide();
$("#myWish").click(function showAlert() {
$("#success-alert").fadeTo(2000, 500).slideUp(500, function() {
$("#success-alert").slideUp(500);
});
});
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="product-options">
<a id="myWish" href="javascript:;" class="btn btn-mini">Add to Wishlist </a>
Purchase
</div>
<div class="alert alert-success" id="success-alert">
<button type="button" class="close" data-dismiss="alert">x</button>
<strong>Success! </strong> Product have added to your wishlist.
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
Using a fadeTo() that is fading to an opacity of 500 in 2 seconds in "I Can Has Kittenz"'s code isn't readable to me. I think it's better using other options like a delay()
$(".alert").delay(4000).slideUp(200, function() {
$(this).alert('close');
});
Why all the other answers use slideUp is just beyond me. As I'm using the fade and in classes to have the alert fade away when closed (or after timeout), I don't want it to "slide up" and conflict with that.
Besides the slideUp method didn't even work. The alert itself didn't show at all. Here's what worked perfectly for me:
$(document).ready(function() {
// show the alert
setTimeout(function() {
$(".alert").alert('close');
}, 2000);
});
I found this to be a better solution
$(".alert-dismissible").fadeTo(2000, 500).slideUp(500, function(){
$(".alert-dismissible").alert('close');
});
one more solution for this
Automatically close or fade away the bootstrap alert message after 5 seconds:
This is the HTML code used to display the message:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="alert alert-danger">
This is an example message...
</div>
<script type="text/javascript">
$(document).ready(function () {
window.setTimeout(function() {
$(".alert").fadeTo(1000, 0).slideUp(1000, function(){
$(this).remove();
});
}, 5000);
});
</script>
It's not limited to showing the message through JS, the message could already be displayed when the page loads.
I know this thread is old, but I just thought I would add my script for Bootstrap 5, incase anyone else needs it
<script>
setTimeout(function() {
bootstrap.Alert.getOrCreateInstance(document.querySelector(".alert")).close();
}, 3000)
</script>
Html:
<div class="alert alert-info alert-dismissible fade show js-alert" role="alert">
Javascript:
if (document.querySelector('.js-alert')) {
document.querySelectorAll('.js-alert').forEach(function($el) {
setTimeout(() => {
$el.classList.remove('show');
}, 2000);
});
}
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
Where fadeTo parameters are fadeTo(speed, opacity)
This is a good approach to show animation in and out using jQuery
$(document).ready(function() {
// show the alert
$(".alert").first().hide().slideDown(500).delay(4000).slideUp(500, function () {
$(this).remove();
});
});
Tiggers automatically and manually when needed
$(function () {
TriggerAlertClose();
});
function TriggerAlertClose() {
window.setTimeout(function () {
$(".alert").fadeTo(1000, 0).slideUp(1000, function () {
$(this).remove();
});
}, 5000);
}
C# Controller:
var result = await _roleManager.CreateAsync(identityRole);
if (result.Succeeded == true)
TempData["roleCreateAlert"] = "Added record successfully";
Razor Page:
#if (TempData["roleCreateAlert"] != null)
{
<div class="alert alert-success">
×
<p>#TempData["roleCreateAlert"]</p>
</div>
}
Any Alert Auto Close:
<script type="text/javascript">
$(".alert").delay(5000).slideUp(200, function () {
$(this).alert('close');
});
</script>
This worked perfectly even though you clicked the button multiple times.
Here I created an onClick function to trigger the closeAlert function.
function closeAlert(){
const alert = document.getElementById('myalert')
alert.style.display = "block"
setTimeout(function(){
alert.style.display = "none"
}, 3000);
}

onClick to get the ID of the clicked button

How do find the id of the button which is being clicked?
<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>
function reply_click()
{
}
You need to send the ID as the function parameters. Do it like this:
<button id="1" onClick="reply_click(this.id)">B1</button>
<button id="2" onClick="reply_click(this.id)">B2</button>
<button id="3" onClick="reply_click(this.id)">B3</button>
<script type="text/javascript">
function reply_click(clicked_id)
{
alert(clicked_id);
}
</script>
This will send the ID this.id as clicked_id which you can use in your function. See it in action here.
In general, things are easier to keep organized if you separate your code and your markup. Define all of your elements, and then in your JavaScript section, define the various actions that should be performed on those elements.
When an event handler is called, it's called within the context of the element that was clicked on. So, the identifier this will refer to the DOM element that you clicked on. You can then access attributes of the element through that identifier.
For example:
<button id="1">Button 1</button>
<button id="2">Button 2</button>
<button id="3">Button 3</button>
<script type="text/javascript">
var reply_click = function()
{
alert("Button clicked, id "+this.id+", text"+this.innerHTML);
}
document.getElementById('1').onclick = reply_click;
document.getElementById('2').onclick = reply_click;
document.getElementById('3').onclick = reply_click;
</script>
USING PURE JAVASCRIPT:
I know it's late but may be for the future people it can help:
In the HTML part:
<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>
In the Javascipt Controller:
function reply_click()
{
alert(event.srcElement.id);
}
This way we don't have to bind the 'id' of the Element at the time of calling the javascript function.
(I think the id attribute needs to start with a letter. Could be wrong.)
You could go for event delegation...
<div onClick="reply_click()">
<button id="1"></button>
<button id="2"></button>
<button id="3"></button>
</div>
function reply_click(e) {
e = e || window.event;
e = e.target || e.srcElement;
if (e.nodeName === 'BUTTON') {
alert(e.id);
}
}
...but that requires you to be relatively comfortable with the wacky event model.
<button id="1" onClick="reply_click(this)"></button>
<button id="2" onClick="reply_click(this)"></button>
<button id="3" onClick="reply_click(this)"></button>
function reply_click(obj)
{
var id = obj.id;
}
How to do it without inline JavaScript or external libraries
it is generally recommended to avoid inline JavaScript, but rarely is there an example of how to do it.
Here is my way of attaching events to buttons.
I'm not entirely happy with how much longer the recommended method is compared to a simple onClick attribute.
Modern browsers (2015+)
Works before the document has finished loading.
Very efficient.
Separates JS from HTML.
JS is in the <head>
const Listen = (doc) => {
return {
on: (type, selector, callback) => {
doc.addEventListener(type, (event)=>{
if(!event.target.matches(selector)) return;
callback.call(event.target, event);
}, false);
}
}
};
Listen(document).on('click', '.btn', function (e) {
let div = document.createElement("div");
div.innerHTML = "click " + e.target.id + "!";
document.body.appendChild(div);
});
<button id="b1" class="btn">Button 1</button>
<button id="b2" class="btn">Button 2</button>
<button id="b3">Do nothing</button>
2014 browsers only
<button class="btn" id="b1">Button</button>
<script>
let OnEvent = (doc) => {
return {
on: (event, className, callback) => {
doc.addEventListener('click', (event)=>{
if(!event.target.classList.contains(className)) return;
callback.call(event.target, event);
}, false);
}
}
};
OnEvent(document).on('click', 'btn', function (e) {
window.console.log(this.id, e);
});
</script>
2013 browsers only
<!DOCTYPE html>
<html>
<head>
<script>
(function(doc){
var hasClass = function(el,className) {
return el.classList.contains(className);
}
doc.addEventListener('click', function(e){
if(hasClass(e.target, 'click-me')){
e.preventDefault();
doSomething.call(e.target, e);
}
});
})(document);
function insertHTML(str){
var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
lastScript.insertAdjacentHTML("beforebegin", str);
}
function doSomething(event){
console.log(this.id); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>
<!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
<script>
insertHTML('<button class="click-me" id="btn1">Button 1</button>');
</script>
<!--Use this when you don't care about broken buttons when javascript is disabled.-->
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me" id="btn2">Button 2</button>
<input class="click-me" type="button" value="Button 3" id="btn3">
<!--Use this when you want to lead the user somewhere when javascript is disabled-->
<a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>
</body>
</html>
Cross-browser
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function(doc){
var cb_addEventListener = function(obj, evt, fnc) {
// W3C model
if (obj.addEventListener) {
obj.addEventListener(evt, fnc, false);
return true;
}
// Microsoft model
else if (obj.attachEvent) {
return obj.attachEvent('on' + evt, fnc);
}
// Browser don't support W3C or MSFT model, go on with traditional
else {
evt = 'on'+evt;
if(typeof obj[evt] === 'function'){
// Object already has a function on traditional
// Let's wrap it with our own function inside another function
fnc = (function(f1,f2){
return function(){
f1.apply(this,arguments);
f2.apply(this,arguments);
}
})(obj[evt], fnc);
}
obj[evt] = fnc;
return true;
}
return false;
};
var hasClass = function(el,className) {
return (' ' + el.className + ' ').indexOf(' ' + className + ' ') > -1;
}
cb_addEventListener(doc, 'click', function(e){
if(hasClass(e.target, 'click-me')){
e.preventDefault ? e.preventDefault() : e.returnValue = false;
doSomething.call(e.target, e);
}
});
})(document);
function insertHTML(str){
var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
lastScript.insertAdjacentHTML("beforebegin", str);
}
function doSomething(event){
console.log(this.id); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>
<!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
<script type="text/javascript">
insertHTML('<button class="click-me" id="btn1">Button 1</button>');
</script>
<!--Use this when you don't care about broken buttons when javascript is disabled.-->
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me" id="btn2">Button 2</button>
<input class="click-me" type="button" value="Button 3" id="btn3">
<!--Use this when you want to lead the user somewhere when javascript is disabled-->
<a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>
</body>
</html>
Cross-browser with jQuery
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function($){
$(document).on('click', '.click-me', function(e){
doSomething.call(this, e);
});
})(jQuery);
function insertHTML(str){
var s = document.getElementsByTagName('script'), lastScript = s[s.length-1];
lastScript.insertAdjacentHTML("beforebegin", str);
}
function doSomething(event){
console.log(this.id); // this will be the clicked element
}
</script>
<!--... other head stuff ...-->
</head>
<body>
<!--Best if you inject the button element with javascript if you plan to support users with javascript disabled-->
<script type="text/javascript">
insertHTML('<button class="click-me" id="btn1">Button 1</button>');
</script>
<!--Use this when you don't care about broken buttons when javascript is disabled.-->
<!--buttons can be used outside of forms https://stackoverflow.com/a/14461672/175071 -->
<button class="click-me" id="btn2">Button 2</button>
<input class="click-me" type="button" value="Button 3" id="btn3">
<!--Use this when you want to lead the user somewhere when javascript is disabled-->
<a class="click-me" href="/path/to/non-js/action" id="btn4">Button 4</a>
</body>
</html>
You can run this before the document is ready, clicking the buttons will work because we attach the event to the document.
Here is a jsfiddle
For some strange reason the insertHTML function does not work in it even though it works in all my browsers.
You can always replace insertHTML with document.write if you don't mind it's drawbacks
<script>
document.write('<button class="click-me" id="btn1">Button 1</button>');
</script>
Sources:
What are alternatives to document.write?
Check if an element contains a class in JavaScript?
event.preventDefault() function not working in IE
https://gist.github.com/eduardocereto/955642
<button id="1" class="clickMe"></button>
<button id="2" class="clickMe"></button>
<button id="3" class="clickMe"></button>
<script>
$('.clickMe').click(function(){
alert(this.id);
});
</script>
If you don't want to pass any arguments to the onclick function, just use event.target to get the clicked element:
<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>
function reply_click()
{
// event.target is the element that is clicked (button in this case).
console.log(event.target.id);
}
With pure javascript you can do the following:
var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i < buttonsCount; i += 1) {
buttons[i].onclick = function(e) {
alert(this.id);
};
}​
check it On JsFiddle
<button id="1" onClick="reply_click()"></button>
<button id="2" onClick="reply_click()"></button>
<button id="3" onClick="reply_click()"></button>
function reply_click()
{
console.log(window.event.target.id)
}
You can simply do it this way:
<input type="button" id="1234" onclick="showId(this.id)" value="click me to show my id"/>
<script type="text/javascript">
function showId(obj) {
var id=obj;
alert(id);
}
This is improvement of Prateek answer - event is pass by parameter so reply_click not need to use global variable (and as far no body presents this variant)
function reply_click(e) {
console.log(e.target.id);
}
<button id="1" onClick="reply_click(event)">B1</button>
<button id="2" onClick="reply_click(event)">B2</button>
<button id="3" onClick="reply_click(event)">B3</button>
Button 1 Button 2 Button 3
var reply_click = function() {
alert("Button clicked, id "+this.id+", text"+this.innerHTML);
}
document.getElementById('1').onclick = reply_click;
document.getElementById('2').onclick = reply_click;
document.getElementById('3').onclick = reply_click;
<button id="1"class="clickMe"></button>
<button id="2" class="clickMe"></button>
<button id="3" class="clickMe"></button>
$('.clickMe').live('click',function(){
var clickedID = this.id;
});
First Way: Send trigger element using this
<button id="btn01" onClick="myFun(this)">B1</button>
<button id="btn02" onClick="myFun(this)">B2</button>
<button id="btn03" onClick="myFun(this)">B3</button>
<script>
function myFun(trigger_element)
{
// Get your element:
var clicked_element = trigger_element
alert(clicked_element.id + "Was clicked!!!");
}
</script>
This way send an object of type: HTMLElement and you get the element itself. you don't need to care if the element has an id or any other property. And it works by itself just fine.
Second Way: Send trigger element id using this.id
<button id="btn01" onClick="myFun(this.id)">B1</button>
<button id="btn02" onClick="myFun(this.id)">B2</button>
<button id="btn03" onClick="myFun(this.id)">B3</button>
<script>
function myFun(clicked_id)
{
// Get your element:
var clicked_element = document.getElementById(clicked_id)
alert(clicked_id + "Was clicked!!!");
}
</script>
This way send an object of type: String and you DO NOT get the element itself. So before use, you need to make sure that your element already has an id.
You mustn't send the element id by yourself such as onClick="myFun(btn02)". it's not CLEAN CODE and it makes your code lose functionality.
in your case:
<button id="1" onClick="reply_click(this.id)">B1</button>
<button id="2" onClick="reply_click(this.id)">B2</button>
<button id="3" onClick="reply_click(this.id)">B3</button>
<script type="text/javascript">
function reply_click(clicked_id)
{
alert(clicked_id);
}
</script>
This will log the id of the element that's been clicked: addFields.
<button id="addFields" onclick="addFields()">+</button>
<script>
function addFields(){
console.log(event.toElement.id)
}
</script>
Although it's 8+ years late, in reply to #Amc_rtty, to get dynamically generated IDs from (my) HTML, I used the index of the php loop to increment the button IDs. I concatenated the same indices to the ID of the input element, hence I ended up with id="tableview1" and button id="1" and so on.
$tableView .= "<td><input type='hidden' value='http://".$_SERVER['HTTP_HOST']."/sql/update.php?id=".$mysql_rows[0]."&table=".$theTable."'id='tableview".$mysql_rows[0]."'><button type='button' onclick='loadDoc(event)' id='".$mysql_rows[0]."'>Edit</button></td>";
In the javascript, I stored the button click in a variable and added it to the element.
function loadDoc(e) {
var btn = e.target.id;
var xhttp = new XMLHttpRequest();
var page = document.getElementById("tableview"+btn).value;
//other Ajax stuff
}
Sorry its a late answer but its really quick if you do this :-
$(document).ready(function() {
$('button').on('click', function() {
alert (this.id);
});
});
This gets the ID of any button clicked.
If you want to just get value of button clicked in a certain place, just put them in container like
<div id = "myButtons"> buttons here </div>
and change the code to :-
$(document).ready(function() {
$('.myButtons button').on('click', function() {
alert (this.id);
});
});
I hope this helps

Categories