Function activation in Element requires a double click to initiate

I've encountered an issue with a web element I'm working on where the click function only triggers after the first click, rendering the initial click ineffective. Here's the code snippet in question:

HTML:

<div>
  <a href="#0" class="packservice" id="rent">Rentals</a>
</div>
<div id="myDIV">
<div class="divinfo">
<div class="servicestxt">
  <h2> Rentals </h2>
<hr>
<br>
  <p>Rent professional beverage serving equipment for your next event. This is our self-serve option.</p><br>
  <a href="#0" id="renBut"> Add to Quote </a>
</div>
</div>
</div>

CSS:

#myDIV {
  display: none;
  color: black;
  padding: 2.5% 71.5% 1.5% 1%;
  background-color: white;
}
a.packservice {
  padding: 1% 97% 1% 1%;
  background: gray;
  opacity: 0.5;
  font-family: 'Oswald', sans-serif;
  font-weight: 900;
  color: white;
  margin-top: .25%;
  display: block;
}
#packhead {
  font-family: 'Oswald', sans-serif;
}
.divinfo {
 width: 250%;
 display: block;
 background-color: white;
 margin-left: 50%;
 overflow: auto;
}

JavaScript:

var renBut = document.getElementById("renBut");
var rent = document.getElementById("rent");

function rentalStore() {
if (renBut.innerHTML=="Add to Quote"){
sessionStorage.setItem("rental", true);
renBut.innerHTML = "Remove from Quote"
} else {
    sessionStorage.removeItem("rental");
    renBut.innerHTML = "Add to Quote";
   }
}

//Create function to hide rentals information div
function myFunction() {
    var x = document.getElementById("myDIV");
    if (x.style.display === "block") {
        x.style.display = "none";
    } else {
        x.style.display = "block";
    }
}

function clickDom() {
// Create event to listen for click and call corresponding function
console.log("Entering clickDom() function");
   if (rent.addEventListener) {
    rent.addEventListener("click", myFunction, false);
  }
}  
function buttonEl() {
if (renBut.addEventListener) {
    renBut.addEventListener("click", rentalStore, false);
  }
}

if (window.addEventListener) {
  //call init() on page load
   console.log("> Adding TC39 Event Listener...");
   window.addEventListener ("load", buttonEl, false);
}

if (window.addEventListener) {
   console.log("> Adding TC39 Event Listener...");
   window.addEventListener ("load", clickDom, false);
} 

I have also added it to a codepen at this link: https://codepen.io/seanbarker182/pen/maexPd

The Javascript here toggles the visibility of the related div when you click 'Rentals' initially, revealing the area containing the 'Add to Quote' button. Strangely enough, the first click seems to do nothing while subsequent clicks work as expected. Any insights into why this behavior occurs?

Answer №1

This issue is rather straightforward, and kudos for including a codepen!

Within your HTML, you currently have the following:

<a href="#0" id="renBut"> Add to Quote </a>

However, in your JS code, it appears as:

if (renBut.innerHTML=="Add to Quote"){

During runtime, renBut.innerHTML will actually be interpreted as " Add to Quote ", with additional spaces on either side. This can be rectified in two ways:

Eliminate HTML Spaces

<a href="#0" id="renBut">Add to Quote</a>

Adjust JavaScript to be whitespace-agnostic

if (renBut.innerHTML.trim()=="Add to Quote"){

The choice between these methods ultimately comes down to personal preference, but I would recommend implementing both for consistency and future-proofing.

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

Exploring the `React.createRef` method using Enzyme for testing purposes

Is there a way to test the following class that utilizes the React.createRef API? I couldn't find any examples online. Has anyone attempted this before? How can I mock the ref effectively? My preference would be to utilize shallow. class Main exten ...

"Unleashing the power of React Native: A single button that reveals three different names

I have a piece of code that changes the name of a button from (KEYWORD) to a different one (KEYNOS) each time it is clicked. How can I modify it to change to a third value (KEYCH), where the default name is (A, B, C... etc), the first click shows Numbers ...

Obtain the text value from an HTML button in JSP code

Here is an HTML tag that I have: <button type="submit" name=<%=s %> value=<%=s %>><%=s%></button> The <%=s %> represents a String with white spaces stored on the server, such as "file one". I am facing an issue with extr ...

The CSS styling is not being rendered correctly on the AngularJS HTML page

Encountering a puzzling situation here. Our angular controller is successfully delivering data to the page, but we are facing an issue with rendering a table due to an unknown number of columns: <table border="1" ng-repeat="table in xc.tables"> ...

matching patterns within HTML div elements

Within my Notepad++ text editor, I am attempting to remove all spaces within a div tag except for those between the comma and the last name. This is what the input looks like: <div class="n"> Joe , Williams </div> And this is the desire ...

Enhance Your Search Bar with Ajax and JQuery for Dynamic Content Updates

My goal is to create a search bar that dynamically loads content, but I want the actual loading of content to start only after the user has finished typing. I attempted a version of this, but it doesn't work because it doesn't take into account ...

Placing information within a nested array with multiple levels of nesting

I'll try to keep this concise, Here is the structure of the schema... import mongoose from 'mongoose' const QuestionSchema = mongoose.Schema({ questionTitle: { type: String, required: " title"}, questionBody: { type: Stri ...

Why won't the display: block CSS style apply to my div element?

Take a look at my code: https://jsfiddle.net/r62p4209/ I created a search bar with company brand name and some buttons on the right, positioned in the center. My aim is for the search bar (from "search by:" to the "Go!" button) to move onto the next lin ...

Unable to view new content as window does not scroll when content fills it up

As I work on developing a roulette system program (more to deter me from betting than to actually bet!), I've encountered an issue with the main window '#results' not scrolling when filled with results. The scroll should always follow the la ...

The video player in HTML may not be compatible with all MP4 files, as some may work while

I have included the following code for embedding mp4 videos on my website: <video class="video" controls="" width="100%" src="videopath/videoname.mp4"></video> Despite using this code for 3 videos, all in mp4 format, only one of them is funct ...

Adding style using CSS to a dynamically generated table row in Vue.js

Currently, I am working with a table that dynamically generates rows using v-for: <table> <tr><th class='name'>Name</th><th>Surname</th></tr> <tr v-for='data in datas'><td class=&a ...

Ways to prevent mouse selection in an input field without disabling or making it read-only

Imagine this scenario: <input type="text"> The task at hand is to prevent text selection within the <input> field. ...

What is the process for calculating and determining the exact area the div should be released?

I am currently developing a drag-and-drop application using only Javascript. I have successfully implemented the dragging functionality, allowing elements to be moved randomly within the page. However, I now face the challenge of creating a drop zone with ...

Retrieving a specific data point from the web address

What is the most efficient way to retrieve values from the window.location.href? For instance, consider this sample URL: http://localhost:3000/brand/1/brandCategory/3. The structure of the route remains consistent, with only the numbers varying based on u ...

Unordered list not floating properly - successful in JSFiddle but not displaying correctly in web browser despite updating Chrome and Firefox

Having trouble floating an unordered list? Check out this jfiddle example that aligns a list next to some text: Here is the updated jfiddle link: https://jsfiddle.net/8qzygaog/ I created a test document based on the example, but it's not working as ...

Issue with React Hot Toast not displaying properly due to being positioned behind the <dialog>

The Challenge of Toast Notifications Visibility with <dialog> Element tl;dr When utilizing the native dialog.showModal() function, the <dialog> element appears to consistently remain on top, which causes toast notifications to be obscured by ...

How about placing one element above another? What sets apart using the margin property versus the position property for achieving this effect?

As I pondered the concept of stacking context, a question arose in my mind. Through my readings, I learned that by not applying any CSS properties that create a stacking context (such as position), it is possible to stack elements on top of each other usin ...

Is it possible to include a local directory as a dependency in the package.json file

As I work on developing an npm package alongside its application, I find myself constantly making small changes to the package. Each time I make a change, I want to run the application again for testing purposes. The package is included as a dependency in ...

Displaying iFrame Border in React Native WebView

When attempting to dynamically add YouTube videos to my React Native app, I decided to utilize a combination of WebView and iFrame due to the incompatibility of the current react-native-youtube component with RN 16+. Although this solution works, the ifram ...

Database query not appearing on node.js route

As a newcomer to javascript and nodejs, I have encountered an issue that I'm hoping to get some clarification on. I am currently working on a simple API and facing difficulties in understanding why a certain behavior is occurring in my code. app.get( ...