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

JS: Initiating a new keypress operation

When I press the Tab key, I want it to do something different instead of its default action. Specifically, I have a text box selected and I would like it to add spaces (essentially making the textarea behave like a text editor). How can I trigger this type ...

Scrapy and Python data gets corrupted by <br> tags causing issues

As I attempt to extract the text from Amazon reviews using scrapy, I encounter an issue. Reviews with multiple lines have their text separated by "< br >" tags within a span element. So, when I try to scrape the first review, I use this line of code: ...

Issue with using tinyMCE alongside jQuery 1.4.2 on Internet Explorer 6

I'm facing an issue with integrating tinyMCE and the new jQuery 1.4.2 on IE6. In our previous projects, we used tinyMCE smoothly with jQuery 1.3.2. However, after the upgrade, a strange problem has arisen. Whenever I click any button in the toolbar (w ...

Having difficulty retrieving data from an HTML file using HTMLEditorKit with Java

Within my HTML code, I have tags structured like this: <div class="author"><a href="/user/1" title="View user profile.">Apple</a> - October 22, 2009 - 01:07</div> I am aiming to retrieve the date, "October 22, 2009 - 01:07" from e ...

Could someone assist me with understanding how to use the Load function in JQuery?

I have a set of links with the class "ajax" that are meant to fetch content from an element with the id "test" in the file "data.html" located in the same directory. This content should then be inserted into the div with the id "content" on my page: <s ...

JavaScript for beginners: show a specified amount of search results and insert a loading indicator at the end

Currently, I have a website that retrieves data from my database using a PHP query. However, the issue I am facing is that there are over 300 entries in my database, resulting in an excessively long displayed page. My main question: How can I restrict ...

Spinning an SVG circle using a group element

I'm interested in rotating an SVG circle without affecting the rotation of other elements. My attempt to rotate the white circle using rotateZ(15deg) resulted in this: This is the progress I've made so far: https://jsfiddle.net/41hrnojs/ <sv ...

Retrieving information from a MYSQL database table and populating a text field with AJAX and PHP

Is there a way to use AJAX to display the data from an array that is called in getword.php into a text field in index.php? Let's take a look at the code below: Here is the code snippet from index.php: <body> <div class="container" ...

The link and source attributes are missing from the .ejs template

I am experiencing an issue where the href and src attributes in my .ejs file are not referencing my local files properly. My setup involves node.js and express. Here is a snippet from the .ejs template that is causing the problem. <head> & ...

Oops! The function 'ModalDemoCtrl' has not been defined, causing an error

Hey there, I'm encountering an error when using angularJS in my project. The project is built on the django framework and does not include any additional JS files. Here are some snippets of my code: JavaScript: {{ ngapp }}.controller("ModalDemoCtrl" ...

Is it possible to locate an element using regex in Python while using Selenium?

Is it possible to interact with a dynamically generated dropdown list using Selenium if I only know the phrase present in its id or class name? Can Selenium locate an element using regex and click on it accordingly? ...

When using PHP, JavaScript, and HTML, you can trigger an image upload immediately after choosing a file using the

I currently have a small form with two buttons - one for browsing and another for uploading an image. I feel that having two separate buttons for this purpose is unnecessary. Is there a way to combine the browse and upload functions into just one button? ...

Choose the offspring of an element using jQuery

Currently, I have a function set up to open a modal dialog and populate it with information from the 'dblclicked' node: $(function(){ $(".delete").live('dblclick', function () { var id = $(this).attr('id'); ...

The NVDA screen reader is unable to detect visually hidden text

In the code snippet below, part of a table is shown where some text is meant to be displayed visibly and some should be visually hidden. However, it seems that the screen reader does not detect the visually hidden text when hovering over it with a mouse. T ...

mysql nodejs function is returning a null value

Kindly review the contents of the dbfn.js file /*This is the database function file*/ var db = require('./connection'); function checkConnection(){ if(db){ console.log('We are connected to the Database server'.bgGreen); ...

Issues with loading times and the rendering of textures in ThreeJS

Having imported a 3D chair object from Blender into ThreeJS, I am encountering some issues. Firstly, the load time is over 40 seconds, which seems excessively long and may be related to Visual Studio. Additionally, the textures of the image are not loadi ...

Using Express.js to serve simple SVG files (Technique involving Cheerio.js)

My goal is to manipulate SVGs before sending them through Express.js. The code snippet I am using is as follows: app.get("/iconic/styles/:style/:base/:icon", function (req, res) { var style = req.params.style; var base = req.params.base; var i ...

Calculating the sum() of a specific attribute in Loopback without the need to iterate through every instance of the object

Within my DummyModel, there are attributes named attOne, attTwo, and attThree. If we want to retrieve all instances of attOne, we can utilize the following query: DummyModel.find({where: {attTwo: 'someValue'}, fields: {attOne: true} }); The ab ...

Vuex getters not displaying expected values in computed properties until entire page has finished loading

When working with computed properties using data fetched by the mapGetters function in my Vuex store, I always encounter the issue of getting an undefined value until the entire page or DOM is fully loaded. For instance, I have an example of an isRegister ...

Creating a text file in Node.js using nodepad formatting

Could anyone assist me with formatting text in a Node.js file to be written to Notepad? Here's the code I'm currently using: const fs = require('fs'); fs.writeFile('write.txt', '', err => {}); var text = [ ...