Replace button text onclick JS - javascript

I'm trying to change button text on button click so that the text changes from 'Copy' to 'Copied!' as part of a custom clipboard setup. Here is the code I'm using:
HTML:
<button id="copyButton2">Copy</button>
JS:
<script>
jQuery(".copyButton2").click(function () {
jQuery(this).text(function(i, v){
return v === 'Copy' ? 'Copied!' : 'Copy'
})
});
</script>
which doesn't appear to be working correctly.
I have also tried modifying this solution to no avail. Is there an obvious reason why this isn't working?

You've set copyButton2 as the id of the element, yet you're using a class selector. You need to prefix the selector with #, not .
Also note that, depending on where you're running the jQuery code, you may also need to include a document.ready handler. Try this:
jQuery(function($) {
$("#copyButton2").click(function() {
$(this).text(function(i, v) {
return v === 'Copy' ? 'Copied!' : 'Copy'
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="copyButton2">Copy</button>

Please use id selector ("#copyButton2") instead of class selector as you have used id for the close button.

Here's a javascript solution while we're at it.
<script>
var testDiv = document.getElementById('test');
testDiv.onclick = function(){
testDiv.innerHTML = "Copied!"
};
</script>

Related

why is button toggle not working with class?

When I change my button toggle from ID-Name to Class-Name, the function is not working anymore. Does anyone know why?
I need a class since this button is multiple times on the page and loads in separately via css and sliders. The function and content is still the same.
$(document).ready(function(){
$('.infoBtn').on('click', function () {
var text=$('.infoBtn').text();
if(text === "info"){
$(this).html('close');
} else{
$(this).text('info');
}
});
});
The issue is your use of selector inside the click event:
$('.infoBtn').text();
Pointy:
Your code should use $(this), not $('.infoBtn') inside the handler.
What you have now will get the text only from the first one on the
page.
If you change that to $(this), it should work as required:
$(this).text();
$(document).ready(function(){
$('.infoBtn').on('click', function(){
//REM: Use $(this) and not $('.infoBtn')!
let text = $(this).text();
$(this).text((text === 'info') ? 'close' : 'info')
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class = 'infoBtn'>initial</button>
<button class = 'infoBtn'>initial</button>

Why is adding event to button not working?

I try to add an EventListener to a button. Here is my code:
<button data-id="g/incider/perry">Kaufen</button>
<script type="text/javascript">
var button = document.getElementById('g/incider/perry');
button.addEventListener(
'click',
function() {
alert("test");
},
false
);
</script>
But the alert is not shown when the button is clicked.
I believe that you are new to the Javascript so will help you out here.
As you see your element <button data-id="g/incider/perry">Kaufen</button> has data-id attribute mentioned but you want to select the element by id as per your code document.getElementById()
Solution: document.getElementById() as the property named it searches for the id attribute in the element so you need to provide id to the element
<button id="uniqueID">Kaufen</button>
and then selecting it with,
const button = document.getElementById('uniqueID');
To Learn more about selectors in JavaScript you can check This Link
Try id instead of data-id.
<button id="g/incider/perry">Kaufen</button>
<script type="text/javascript">
var button = document.getElementById('g/incider/perry');
button.addEventListener(
'click',
function() {
alert("test");
},
false
);
</script>
If you want to use data-id for some reason you have to use the getAttribute() function to get the value of an attribute otherwise just stick with id.
const button = document.getElementById('g/incider/perry');
button.addEventListener('click', () =>
alert("test");
}, false);
<button id="g/incider/perry">Kaufen</button>

Append input box with JQuery

I was trying to add text into field with id #shouttext, but i need to trim value from onclick event which is just after (' and also delete ') symbols.
So if i have
<img src="images/smilies/at.png" alt="" title="" class="smilie smilie_9 smilie_pointer" onclick="MyBBEditor.insertText(':at:');">
I want to get
:at:
and add it to input with #shouttext id. Below is my code, which doesn't work - and i think its blocked by defined onclick value, which i was trying to remove.
<script type="text/javascript">
$( document ).ready(function() {
$('.smilie').click(function()
{
var s1,s1;
s1=attr("onclick");
s1=s1.replace('MyBBEditor.insertText(\'', '');
s2=s1.replace('\')', '');
$('.smilie').attr('onclick','').unbind('click')
$('#shouttext').val($('#shouttext').val()+s2);
})
});
</script>
Thanks for any help in advance!
you could try also:
var str = $(".smilie").attr("onclick").split("'")[1];
to get the :at: try it here: fiddle
now you can use it here:
$('.smilie').unbind("click");
$('.smilie').click(function() {
var str = $(".smilie").attr("onclick").split("'")[1];
$('#shouttext').val($('#shouttext').val() + "" + str);
});
or how #eg_dac says, you can override the click event with $.on()
instead of unbinding it in the click, you can do
$(".smilie").attr("onclick", ""); // clear the already declared attribute.
$(".smilie").on("click", function(){
$('#shouttext').val($('#shouttext').val()+s2);
});
Example found here http://jsfiddle.net/meougz1L/
$("img").attr("onclick","");
$("img").on("click", function(){
alert("click event overridden");
});

Add an attribute to html element with javascript on page load?

What I've tried:
function addAttribute(){
document.getElementById('myid')...
};
window.onload = addAttribute;
How can I add add the attribute to my element with id="myid" ?
document.getElementById('telheaderid').yourattribute = "your_value";
For instance
document.getElementById('telheaderid').value = "your_value";
Using jQuery:
$('#telheaderid').attr('value', 'your_value');
EDIT:
Focus is the event that fires up when an element get focused or for instance when we click on the textarea it highlights thats the time.
Using jQuery:
$('#telheaderid').focus(function() {
$(this).val('');
// run any code when the textarea get focused
});
Using plain javascript:
document.getElementById('telheaderid').addEventListener('focus', function() {
this.value = "";
});
Use this:
document.getElementById('telheaderid').setAttribute('class','YourAttribute')
The W3C standard way:
function functionAddAttribute(){
document.getElementById('telheaderid').setAttribute('attributeName', 'attributeValue');
};
window.onload = functionAddAttribute;
for IE:
function functionAddAttribute(){
document.getElementById('telheaderid').attributeName = 'attributeValue';
};
window.onload = functionAddAttribute;
Enjoy your code!

Optimizing jQuery Spoiler Button

HTML
<!doctype html>
<html>
<head>
</head>
<body>
<button id="b1" type="button">Show Spoiler</button>
<p id="p1" style="display:none"> This is a damn paragraph.</p>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
JS
function bindEvent(element, eventName, eventHandler) {
var el = $(element)[0];
if (el.addEventListener) {
el.addEventListener(eventName, eventHandler, false)
} else if (el.attachEvent) {
el.attachEvent('on'+eventName, eventHandler);
}
}
bindEvent('#b1', 'click', function() {
$('#p1').toggle('blind');
if ($('#b1').text() == 'Show Spoiler') {
$('#b1').text('Hide Spoiler');
} else if ($('#b1').text() == 'Hide Spoiler') {
$('#b1').text('Show Spoiler');
}
});
I'm new to jQuery and Javascript so I made this simple script to show and hide a paragraph and to change the button texts whenever clicked. My problem is that this seems a bit clunky. Is there a better, shorter, and simpler way to achieve the same result?
First of all, jQuery already normalizes DOM event listeners for you across browsers, so your bindEvent function isn't necessary anymore. Here's the short way, using some stuff you can look up yourself in the jQuery API, to do what you're doing.
var $b1 = $('#b1')
, $p1 = $('#p1')
, hideText = 'Hide Spoiler'
, showText = 'Show Spoiler'
$b1.on('click',function() {
var text = $b1.text()
, newText = text === showText ? hideText : showText
$p1.toggle('blind')
$b1.text(newText)
})
Here are a few things to notice:
Your example function assumes a single spoiler #p1 and a single reveal button #b1. In production, this will probably be based on classes, like .spoiler and .spoiler-trigger, and there will be multiple spoilers on a page. In that case, you'll need to get the value of this. In this example let's assume that the reveal button is always a sibling of the spoiler itself.
$('.spoiler-trigger').on('click',function() {
var $this = $(this)
, $thisSpoiler = $this.siblings('.spoiler').eq(0)
, text = $this.text()
, newText = text === showText ? hideText : showText
$thisSpoiler.toggle('blind')
$this.text(newText)
})
The jQuery .on method is the cross-browser event listener function that you'll want to start using.
jQuery selectors we use repeatedly, like $(this) or $('#b1'), should be cached in local variables for performance.
I'm using a ternary conditional instead of an if statement to determine what the show/hide text should be, because in this very simple case I consider it more readable.
You can make this work with simple 3 lines of code using awesome jquery. trigger the button click event, and on click -> toggle the element 'P'. This should help : working demo
$("#b1").click(function () {
$("#p1").toggle('slow');
});​

Categories