Creating a function in Javascript to adjust opacity when clicked

I am looking to create a function that controls opacity when a particular element is clicked. I tried the following code, but it did not have the desired effect.

var changeOpacity = function(id) {
  document.getElementById(id).style.opacity = "1";
};
<head>
  <link rel="stylesheet" href="style.css" />
  <script src="https://kit.fontawesome.com/71fb624cb4.js" crossorigin="anonymous"></script>
  <link href="https://fonts.googleapis.com/css2?family=Lato&display=swap" rel="stylesheet" />
  <script src="js.js"></script>
</head>

<body>
  <div class="container">
    <a class="home h" id="h" onclick="changeOpacity(" h ")"><i class="fas fa-home"></i>Home</a>
    <a class="home acc"><i class="far fa-user-circle"></i></i>Account</a>
    <a class="home fli"><i class="fas fa-fighter-jet"></i>Flights</a>
  </div>
</body>

</html>

Answer №1

To avoid issues with the id quotes, make sure to escape them properly. If you are not using a JS variable within the id like shown here: "op("+h+")", consider using single quotes or follow the suggestion provided in another question:

onclick="op('h')"

Answer №2

It's essential to always check the error console for any issues. Don't simply assume that everything will function correctly.

The presence of invalid HTML is causing a JavaScript syntax error to occur when the onclick event is triggered.

onclick="op("h")"

Having quotes within quotes creates confusion for the parser - it needs to be clear which quotes are related to each other. To solve this issue, you can escape the inner quotes with \ or use single quotes instead.

onclick="op(\"h\")"
onclick="op('h')"

Answer №3

To implement a click event, you can utilize the onclick attribute. If you want to style links, consider the following approach:

document.getElementById("h").style.opacity = 1;

function adjustOpacity(el) {
  el.style.opacity -= 0.1;
}
<head>
  <link rel="stylesheet" href="style.css" />
  <script
    src="https://kit.fontawesome.com/71fb624cb4.js"
    crossorigin="anonymous"
  ></script>
  <link
    href="https://fonts.googleapis.com/css2?family=Lato&display=swap"
    rel="stylesheet"
  />
  <script src="js.js"></script> 
</head>
<body>
  <div class="container">
    <a class="home h" id="h" onclick="adjustOpacity(this)"><i class="fas fa-home"></i>Home</a>
    <a class="home acc"><i class="far fa-user-circle"></i></i>Account</a>
    <a class="home fli"><i class="fas fa-fighter-jet"></i>Flights</a>
  </div>
</body>
</html>

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

Tips for getting the setInterval function to work with a progress bar even when a tab is not in focus

After browsing through similar questions, I couldn't find the answer I was looking for. As a newbie in programming experimenting with JavaScript Progress Bar, I encountered an issue where the progress bar would pause and the counter wouldn't coun ...

The buffer for the operation `users.insertOne()` exceeded the timeout limit of 10000 milliseconds, resulting in a Mongoose

I am currently utilizing a generator that can be found at this Github link Project repository: Github Project Link Encountering an issue when attempting to input a user using the `MASTER_KEY`, I keep receiving the following error message: MongooseError ...

What is the best way to position a div below a sticky navbar?

I have implemented a sticky navbar on my index page along with JavaScript code that adjusts the navbar position based on screen height. When scrolling, the navbar sticks to the top of the page, but the flipping cube overlaps with the sticky navbar. How can ...

Is there a way to access the dimensions of a Bootstrap 4 popover?

I'm attempting to dynamically retrieve the height/width of the Bootstrap popover. I have the context in which I'm trying to grab the height/width: console.log(context); console.log(context.getBoundingClientRect().height); console.log(context.get ...

Creating a tool to display mouse coordinates as a pointer on an HTML5 canvas

I'm struggling with mouse coordinates while working on canvas in HTML5. My approach involves using JavaScript for drawing on the canvas. Below is my current code to track the mouse pointer within the canvas: $('#canvasID').mousedown(functi ...

Find the mean of two values entered by the user using JavaScript

I'm sorry for asking such a basic question, but I've been struggling to get this code to work for quite some time now. I'm ashamed to admit how long I've spent trying to figure it out and how many related StackOverflow questions I ...

Tips on choosing one specific JSON object from a group and exploring its structure in Python

Looking for guidance to access a specific javascript element named SOURCE.pdp.propertyJSON and extract its attributes in a Pythonic way from a webpage filled with different script elements. Browse through the HTML source code below to get an idea and then ...

Retrieve data using ajax within an mvc framework

I am facing an issue where I am unable to receive the data sent with AJAX jQuery to a .NET server as a parameter, modify it in memory, and then convert it to JSON. Any assistance in resolving this problem would be greatly appreciated. JAVASCRIPT document ...

I am unable to achieve negative X degree rotation of the image while using mousemove to rotate it

I need assistance with moving a picture in 3D. I want the offsetX of the mouse to be positive when it's past half of the picture, and negative otherwise. How can I achieve this effect for rotation degrees? This is what I have tried: $('#img ...

Certain individuals are experiencing difficulties accessing my Google application

I have created a node.js application with a Google login feature using the following packages: "passport": "^0.3.2" "passport-google-oauth": "^1.0.0" However, I am facing an issue where only a few users are able to access this feature. Below is the code ...

Dynamically Add Routes in ExpressJS During Runtime

I am interested in creating routes dynamically at runtime, but I'm not entirely sure how to do it. Currently, I have the following code snippet: var app = express(); function CreateRoute(route){ app.use(route, require('./routes/customchat.js&ap ...

How to modify a value in a document within a MongoDB collection

I'm having an issue with updating the 'panel' field in both the cards collection and projects collection. Here is my code snippet: const project = await Project.findOne({"code":currentUser.groupcode}); // this works const ...

Polymer event / callback for appending new child nodes

My current project involves creating a custom element, let's call it <parent-element>, that performs specific actions based on the presence of its childNodes. When I define the element like this: <parent-element> <div> </div&g ...

Issue with GMap Compatibility on Specific Web Browsers

I'm currently facing an issue with implementing gMap [1] on a website. The map is functioning properly in Chrome and Safari, but it fails to display in Firefox, IE, and Opera (latest versions of all). I have ensured that the Google Map API key loads a ...

Discover the offsetTop value of a child element in React using TypeScript

How can I retrieve the offsetTop of React children in Typescript? Here is an example of my component: export default class FadeIn extends Component { private onScroll = () => { React.Children.forEach(this.props.children, child => { // G ...

The success:function() is not being triggered in the Ajax response with jQuery version 1.8.3

My code is not calling success:function() in the Ajax response when using jQuery 1.8.3, but it works perfectly with jQuery 1.4.2. Here is the code snippet: <script type="text/javascript"> $(document).ready(function(){ $("#usn").on('keyup&a ...

Screening strings and arrays based on multiple criteria

My code is below and I am trying to have the bot check for two specific conditions in the user's message. The message must contain "how" plus either "doing" or "bread". It works perfectly when using only "doing" but not when adding the "bread" conditi ...

Database storing incorrect date values

After successfully displaying the current year and month in a textbox, an issue arises when submitting the data to the database. Instead of the expected value from the textbox, it defaults to 2014. What could be causing this discrepancy? function YearM ...

Whenever I repeatedly click the button, the array will store a new value. My goal is for it to collect and store all values obtained from the function

After retrieving data from the listAPI value using an API, the output is displayed as follows: //output - console.log(listAPI) 5) [{…}, {…}, {…}, {…}, {…}] 0: {id: "1", name: "name 1", active: "true"} 1: {id: " ...

Customize the background color in VueJS based on user roles

I am currently working on a vuejs project with different user levels. In the "user" level (and public area), there is a background image, while in the "admin" level, a plain white background is displayed. I have read that using style tags in the template ...