JavaScript Button Style change on click - javascript

I have put together this piece of JavaScript, but I am struggling with the code as I'm a newbie. What I want to do is when a button is clicked it will change the background color opacity. The code below does this, but now I want the button to be reverted to the normal state when I click it again.
How can I do this? Thanks..
Normal state: background="rgba(255,0,0,0.8)"; Pressed state:
background="rgba(255,0,0,0.6)";
function highlight(id) {
document.getElementById(id).style.background="rgba(255,0,0,0.6)";
}

I would use a CSS class:
.opacityClicked{
background:rgba(255,0,0,0.8);
}
.opacityDefault{
background:rgba(255,0,0,0.6);
}
And change your function to:
function highlight(id) {
var element = document.getElementById(id);
element.class = (element.class == "opacityClicked") ? "opacityDefault" : "opacityClicked";
}
Or if you want to use only JavaScript
var isClicked = false;
function highlight(id) {
isClicked = !isClicked;
var element = document.getElementById(id);
element.style.background = (isClicked == true) ? "rgba(255,0,0,0.6)" : "rgba(255,0,0,0.8)";
}
Update(See comments: if you use 2 buttons):
var buttonClicked = null;
function highlight(id) {
if(buttonClicked != null)
{
buttonClicked.style.background = "rgba(255,0,0,0.8)";
}
buttonClicked = document.getElementById(id);
buttonClicked.style.background = "rgba(255,0,0,0.6)";
}

You could do something really quick like this:
First, add a hidden input element to your page like so:
<input type="button" id="foobar" value="FooBar!" onclick="highlight('foobar')" style="background-color:rgba(255,0,0,0.8);" />
<input type="hidden" id="one_neg_one" value="1" /> <= hidden element
Next, put this in your highlight function:
function highlight(id) {
var a = 7;
var o = document.getElementById("one_neg_one");
var newa = (a + (parseInt(o.value) * -1)) * 0.1;
document.getElementById(id).style.background="rgba(255,0,0," + newa + ")";
o.value = o.value * -1;
}
That should work, although I agree with a previous answer that you should use a css class for this.

#Ruben-J answer works fine. There is a syntax error though - you should instead use element.className rather than element.class.
https://developer.mozilla.org/en-US/docs/Web/API/Element/className
Below is an updated answer using the correct syntax:
function highlight(id) {
var element = document.getElementById(id);
element.className = (element.className == "opacityClicked") ? "opacityDefault" : "opacityClicked";
}
Also noticed that this answer doesn't show the HTML. Make sure to pass through the id element, not the name of the id.

Related

how to exchange the attribute values simultaneously on single click event using jQuery

I want to replace #cardvieo_localstream with #cardvideo_remotestream at the first click, again I click the same element, I want to change #cardvideo_remotestream back #cardvieo_localstream, I'm not sharp at jQuery yet, but I'm trying to learn. I appreciate all help I can get.
I've try this code but working on first click. but not working on second click
$('.video-list .videoWrap').on('click', function() {
var $thisVideoWrap = $(this).find('.video-list .videoWrap');
var $mainVideoWrap = $('.mainVideoWrap');
if ($(this).attr('id') === '#cardvideo_localStream') {
$(this).attr('id', '#cardvideo_remotestream');
}
else if($(this).attr('id') == '#cardvideo_localStream') {
$(this).attr('id', '#cardvideo_local');
$mainVideoWrap.attr('id', 'cardvideo_remotestream');
}
});
Don't change An Id Attribute because of id is a unique value Only use the Classname, I swap the elements successfully
// using jQuery
var initVideoSwapping = function () {
// check if there is an element first
if ($('.video-list .videoWrap').length > 0) {
$('.video-list .videoWrap').on('click', function () {
var $thisVideo = $(this).find('video')[0];
var $mainVideo = $('.mainVideoWrap').find('video')[0];
swapNodes($thisVideo, $mainVideo)
});
}
}
function swapNodes(a, b) {
var aparent = a.parentNode;
var asibling = a.nextSibling === b ? a : a.nextSibling;
b.parentNode.insertBefore(a, b);
aparent.insertBefore(b, asibling);
}
$(function () {
initVideoSwapping();
});

bind javascript function to input control on window load

I amm develloping an web form with multiple text box with same css class.
and i want to bind a specific method to all these textboxes who use that class.
belows are my codes
window.onload = function ()
{
var tObj = document.getElementsByClassName('exa');
for (var i = 0; i < tObj.length; i++) {
tObj[i].onblur(convertAmount(event,this));
}
}
the another function 'convertAmount()' is below
function convertAmount(evt, obj) {
if (obj.value != "") {
var num = parseFloat(obj.value);
num = Math.round((num + 0.00001) * 100) / 100;
obj.value = num.toFixed(2);
}
else {
obj.value = "0.00";
}
}
html codes
<div>
<input type="text" id="finalvalue" class="exa"/>
<input type="text" id="grossvalue" class="exa"/>
<div>
when browser load first time only '0.00' values are coming on those text boxes. but when i type some values on those text boxes and press tab its not working! please help what is wrong here
As commented before, you should assign a eventHandler and not pass it as callback.
So you code would be:
tObj[i].onblur = convertAmount.bind(this, event, this);
Also, event is default argument for any eventListener and current object/element is automatically binded to it, so above code can be simplified to
tObj[i].onblur = convertAmount;
This will bind the context and you will get all properties in this.
Sample Fiddle
Note: you should use addEventListener instead. onBlur = will replace all previous events. addEventListener will add another one.
Sample Fiddle
I hope this link helpful to you.
<div>
<input type="text" id="finalvalue" class="exa"/>
<input type="text" id="grossvalue" class="exa"/>
<div>
$(document).ready(function(){
$('.exa').each(function(index,value){
$(this).attr('onblur',convertAmount(event,$(this)))
})
})
function convertAmount(evt, obj) {
if (obj != "") {
$(obj).val('0.00')
}
else {
$(obj).val('0.00')
}
}

How to change class back after onclick

I'm creating a spoiler-tag script where the user clicks on spoiler text, the text will either blank out or change font-color depending on the class assigned to it. I'm rather a noob at Javascript.
My script only works when I click on the spoilered text when it is blank- so when I have already clicked on it, I can't reclick to change it back.
Here is the code that works:
// Hide Spoiler Individually
var singleHidden = document.getElementsByClassName("hidden");
var hideMe = function () {
var attribute = this.getAttribute("hidden");
this.className = "show";
};
for (var i = 0; i < singleHidden.length; i++) {
singleHidden[i].addEventListener("click", hideMe, false)
};
Here's a link on jsfiddle.
https://jsfiddle.net/o94c00hb/
Try this:
var hideMe = function() {
if(this.className == "hidden")
this.className = "show"
else
this.className = "hidden"
};
If you're not opposed to using jquery i would do something like this:
$('.hidden').on('click', function(){
$(this).toggleClass('show');
});
JSFIDDLE

Displaying a hidden text box when a particular option value selected

I am trying to make a hidden text-box visible when a particular option value is selected, It works when there are multiple options available obviously because it responds to onChange. How can I get it to work if that is the only option present, the first select box in my Example.
Js Fiddle - http://jsfiddle.net/8bm9R/
This is my Js function
function showOther(fieldObj, otherFieldID) {
var fieldValue = fieldObj.options[fieldObj.selectedIndex].value;
var otherFieldObj = document.getElementById(otherFieldID);
otherFieldObj.style.visibility = (fieldValue == 'other') ? '' : 'hidden';
return;
}
I've updated the JsFiddle:
Basically JsFiddle is misused, the function should be set to be wrapped in the header instead of 'onLoad'.
jsfiddle.net/8bm9R/2/
function showOther(fieldObj, otherFieldID)
{
var fieldValue = fieldObj.options[fieldObj.selectedIndex].value;
var otherFieldObj = document.getElementById(otherFieldID);
otherFieldObj.style.visibility = (fieldValue=='other') ? '' : 'hidden';
return;
}
Cheers
$("select").change(function() {
if($(this).val() == "expected_value") {
otherFieldObj.style.visibility = "visible"
}
else {
otherFieldObj.style.visibility = "hidden"
}
});

Programmatic creation of text input with JavaScript

I am currently learning JavaScript, and I got stuck at the following problems: I have tried to dynamically create an input of type text from JavaScript and to set its onChange method, but it is fired only when the page is loaded. In addition, document.onload does not work for creating my input, but window.onload does, although the tutorials I read claim that these two are almost the same thing. The code is the following:
<html>
<head>
<script type="text/javascript">
function f(value) {
alert(value);
return true;
}
window.onload = function() {
if (document.getElementById("cloned") == null) {
var clonedInput = document.createElement('input');
clonedInput.type = 'text';
clonedInput.value = "";
clonedInput.id = 'cloned';
clonedInput.size = 20;
clonedInput.onChange = f(clonedInput.value);
var lastChild = document.getElementById("parent");
document.body.insertBefore(clonedInput, lastChild);
}
};
</script>
</head>
<body>
<input id="toClone" type="text"/>
<div id="parent"></div>
</body>
</html>
f(clonedInput.value) calls the function immediately and sets its return value (which is true in this case) as event handler.
You want to use an anonymous function:
clonedInput.onchange = function(){ f(this.value); };
Note: While HTML attributes are case-insensitive, JavaScript object properties are not.
You can actually clone the existing input element:
if (document.getElementById("cloned") == null) {
var clonedInput = document.getElementById("toClone").cloneNode(true);
clonedInput.id = 'cloned';
clonedInput.onchange = f;
var lastChild = document.getElementById("parent");
document.body.insertBefore(clonedInput, lastChild);
}
Now to read the value change f to this:
function f() {
var value = this.value;
alert(value);
return true;
}
Edit: to make the cloned input reflect the first "live" you'll have to attach couple of events:
if (document.getElementById("cloned") == null) {
var orgInput = document.getElementById("toClone");
var clonedInput = orgInput.cloneNode(true);
clonedInput.id = 'cloned';
clonedInput.onchange = f;
orgInput.onkeypress = ReflectValue;
orgInput.onchange = ReflectValue;
var lastChild = document.getElementById("parent");
document.body.insertBefore(clonedInput, lastChild);
}
Then have this function:
function ReflectValue() {
var cloned = document.getElementById("cloned");
cloned.value = this.value;
}
Now whenever user type in the first input, it will reflect in the second input, and whenever user focus out it will also reflect any "non-keyboard" changes like pasting text.

Categories