Styling checkboxes and adding onClick functionality in JavaScript

I want to customize the appearance of my checkboxes while still maintaining an onClick function. I came across a code for styling that hides the actual checkbox and stylizes the label, but it seems to disable the JavaScript onClick function. Is there a way to make both work together?

CSS

input[type=checkbox] {
margin:10px;
position: absolute;
z-index: -1;
}
input[type=checkbox] + label {
display:inline-block;
margin:-2px;
padding: 4px 12px;
margin-bottom: 0;
font-size: 18px;
color:#8C8C8C;
font-family:"Goudy Old Style";
text-align: center;
vertical-align: middle;
cursor: pointer;
background-color: #f5f5f5;
background-image: -moz-linear-gradient(top,#fff,#e6e6e6);
background-image: -webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));
background-image: -webkit-linear-gradient(top,#fff,#e6e6e6);
background-image: -o-linear-gradient(top,#fff,#e6e6e6);
background-image: linear-gradient(to bottom,#fff,#e6e6e6);
background-repeat: repeat-x;
border: 1px solid #ccc;
border-color: #e6e6e6 #e6e6e6 #bfbfbf;
border-color: rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);
border-bottom-color: #b3b3b3;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);
filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
-webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
-moz-box-shadow: inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
box-shadow: inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
}

input[type=checkbox]:checked + label {
   background-image: none;
outline: 0;
-webkit-box-shadow: inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);
-moz-box-shadow: inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);
box-shadow: inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);
    background-color:#e0e0e0;
    color:#FBFBFB;
}

HTML

<input type="checkbox" id="checkbox1" name="type_of_contact" value="Fax" >
   <label for="checkbox1">Fax</label>
<input type="checkbox" id="checkbox2" name="type_of_contact"value="Mail" onclick="myMail()">
   <label for="checkbox2">Mail</label>

JavaScript

function myMail() {
        if (document.getElementById('mail').checked) {
        document.getElementById('entermail').style.display = "block";
    } else {
        document.getElementById('entermail').style.display = "none";
    }
}

Answer №1

When styling your CSS, consider adding a z-index of -1 to the checkbox to place it behind the label. Additionally, attach your onClick Event to the Label instead of the Checkbox for better functionality.

Answer №2

The HTML code was off. After fixing the IDs, everything fell into place perfectly.

Answer №3

Create a custom function and attach it to the global window object.

window.myCustomFunction = function() {
    console.log('This is a test function');
};

Check out the demonstration here: http://example.com/demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a Stylish Tilted Effect on Div Sides using CSS

I am attempting to create a specific shape using clip-path: polygon, but I am struggling to understand the documentation. The properties for this shape are unclear to me - what do the values represent in clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%) ...

Interact with various div elements bearing the same class name through mouse movements

I am trying to implement a mousemove effect on multiple divs with the same class name but facing an issue where the mouse position doesn't restart inside each div. If you want to see a demo of what I'm describing, click here. Below is the code ...

Adding a watermark or overlay to an image using JavaScript and PHP

I am working on a game where users have to guess which quadrant a meteor will hit. After each round, I want to display an image of a "crater" on the map based on the randomly generated quadrant using PHP's rand(1,4) function. The map is represented a ...

Unexpected database query result in Node.js

In my newuser.js file for a node.js environment with a mongodb database managed through mongoose, I have the following code: //newuser.js //This code is responsible for creating new user documents in the database and requires a GET parameter along with a ...

In TypeScript, a mapped type is not allowed to define properties or methods

My challenge involves defining an interface with keys that match a specific enum key type. However, when I attempt to declare this type, I encounter the following error message: A mapped type may not declare properties or methods. Below is the code snip ...

Ways to customize decoration in Material UI TextField

Struggling to adjust the default 14px padding-left applied by startAdornment in order to make the adornment occupy half of the TextField. Having trouble styling the startAdornment overall. Attempts to style the div itself have been partially successful, b ...

Only the initial external CSS ID is functional, while the second one is inactive

I am facing an issue with my table where I have applied an external CSS that uses alternating shaded rows. My aim is to have specific table cells with different background and font colors - one cell with a green background and red font, and another with a ...

What factors cause variations in script behavior related to the DOM across different browsers?

When looking at the code below, it's evident that its behavior can vary depending on the browser being used. It appears that there are instances where the DOM is not fully loaded despite using $(document).ready or similar checks. In Firefox, the "els ...

Reverse the text alteration when the user leaves the field without confirming

Upon exiting a text box, I aim to display a confirmation dialogue inquiring whether the user is certain about making a change. If they select no, I would prefer for the text box to revert back to its original state. Is there an uncomplicated method to ach ...

``Do not forget to close the modal window by clicking outside of it or

I am looking for a way to close the modal window either when a user clicks outside of it or presses the escape key on the keyboard. Despite searching through numerous posts on SO regarding this issue, I have been unable to find a solution that works with ...

Ways to adjust the CSS height of a fluid body and flexible footer

In a nutshell, I'm dealing with 3 elements: <div> <Header/> </div> <div> <Body/> </div> <div> <Footer/> </div> The header has a fixed height. ...

Displaying the HTTP response on the webpage renders as plain text

I encountered an issue while trying to forward a request from a proxy server and display the response in the browser. When I use res.write(data) to render the response, it appears as plaintext instead of rendered HTML: http.createServer(function targetSer ...

Autofill Text Input with React Material-UI

For my current project, I am utilizing Material UI and React. Each TextField in the project has a button next to it, and when the button is clicked, I want it to retrieve the value of its corresponding TextField and set that value as the input for another ...

Try to showcase the contents of a JSON file

Below is the JSON data that I need to reference: { "webservice_status": { "status": "SUCCESS", "message": "" }, "dailyroster": [ { "webservice_status": null, "recordNumber": "3014973", "first_date": "2016-04-27", ...

Retrieve childNodes of the Select All input using jQuery from the container node with the class name "container"

I am trying to retrieve the text value of all the childNodes within the container of the corresponding input when the Select All checkbox is checked. Currently, my code captures the text inside each input label. However, it only logs the label (e.g. &apos ...

How to properly handle file uploads and get the correct image path from Node Js (Express) to React Js?

Currently, I am working on my local system developing a file upload feature using node js. My project file structure looks like this: Project ..client .... source code of React App ..Server ....uploads ......avatar ........image.png ....index.js In this ...

Form containing a pair of buttons

I am attempting to design multiple forms with two buttons, each of which will submit the form to a different script. One button will use ajax for submission, while the other will simply submit the form without ajax. <?php foreach($objects as $object) : ...

An erroneous if statement in JavaScript is being triggered

I have a series of if statements that output different strings from corresponding lists based on the input (feelsLike). View Code Initially, it identifies the range in which feelsLike falls and then concatenates all items in the list into the string. Whe ...

Using a custom function with Node.js middleware

Query regarding express middleware. Assume I have a route structured as shown below: router.route('/replies/:board') .post(bodyThreadIdVal, textVal, passVal, replyHandler.postReply) Now suppose I want to separate the first three middleware ...

Inject customized CSS following third-party plugin stylesheets in WordPress

I am currently exploring methods to incorporate a custom.css file after the loading of a third-party plugin. I am familiar with registering and enqueueing CSS files in functions.php. Is it possible to establish a dependency for the stylesheets of the thi ...