What is the best way to trigger an onclick event for an input element with a type of "image"?

In the code I'm working on, there's an input of type "Image".

<div class="icon" id="button_dictionary">
    <form>
        <input class="buttonDictionary" type="image" src="icone_dicionario.jpg" value="" id="inputDictionary"> 
        <label for="inputDictionary">Dictionary</label>
    </form>
</div>

My goal is to have a form appear when the user clicks on this input:

<form action="http://www.google.pt/search" id="form-dictionary">
     (...)
</form>

I've written a Javascript function to achieve this:

function showsDictionaryForm(){
            if(document.querySelector('#form-dictionary').style.display == "none")
                document.querySelector('#form-dictionary').style.display = "inline-block";
            else
                document.querySelector('#form-dictionary').style.display = "none";
}

The problem arises when attempting to handle the onClick event for the input. The function works fine for "submit" input types.

Attempts to solve:

I tried this:

document.querySelector('#button_dictionary').onclick = showsDictionaryForm;

as well as this with return false added at the end of the function.

 <input class="buttonDictionary" type="image" src="icone_dicionario.jpg" value="" id="inputDictionary" onClick="showsDictionaryForm()">

However, none of these approaches worked effectively. The form appears briefly but disappears quickly afterwards. It seems like the form gets rendered, but upon the button submission, the page reloads causing it to vanish again.

Answer №1

In the handleDictionaryEvent(event) function, ensure to include event.stopPropagation() in order to prevent the default behavior (such as form submission).

Instead of using inline styles within the handleDictionaryEvent function, consider utilizing class manipulation for a more organized approach. You can define a global class:

.hidden {
  display: none !important;
}

This class can then be applied to show/hide the dictionaryForm.

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

Creating a custom decision tree in Angular/JS/TypeScript: A step-by-step guide

My current project involves designing a user interface that enables users to develop a decision tree through drag-and-drop functionality. I am considering utilizing GoJS, as showcased in this sample: GoJS IVR Tree. However, I am facing challenges in figuri ...

Executing a file function from another within a module function in ReactJS

I need to utilize the functions that are defined in the apiGet.js file: export let apiGet = () => { return 'File One'; } These functions are being called in another module called brand.js. Here is the code snippet: require("../action ...

bind a class property dynamically in real-time

I need to dynamically generate a TypeScript class and then add a property to it on the go. The property could be of any type like a function, Promise, etc., and should use this with the intention that it refers to the class itself. let MyClass = class{ ...

Can you provide an alternative code to access an element with the id of 'something' using vanilla JavaScript instead of jQuery's $('#something') syntax

Why am I seeing different console output for $('#list') and document.getElementById("list")? Here is the console printout: console.log($('#list')); console.log(document.getElementById("list")); However, the actual output in the cons ...

An internal server error has occurred within the asp.net framework, resulting in

Seeking Solution: Currently, I am in the process of developing an application where I have implemented an HTML select list to choose a category. Using AJAX web method, I am trying to retrieve items and their respective images based on the selected category ...

What is the process for incorporating data- attributes into ExtJs-generated HTML?

Currently working with ExtJs 4.1. In the process of developing a panel (for instance), I want to incorporate one or more "data-" attributes in the generated html, such as data-intro="some text" data-step="1" Any tips on how to achieve this? ...

Displaying an image gradually as the user moves down the page

Recently, I came across this fascinating website: As you scroll down, the images on the site gradually unveil more details, which caught my attention. This unique effect is not something commonly seen on websites, and I'm curious to learn how it is ...

Anchor validation across various spans

Here is the HTML code snippet I am working with: <p class="main-text"> <span>Lorem Ipsum</span> <span>Lorem Ipsum</span> <span>Lorem Ipsum</span> <span>Lorem Ipsum</span> ...

View the edited image preview instantly upon selecting the image

I have selected an image and previewed it before submitting the form. However, now I wish to be able to edit the file immediately after selecting it, preview the changes, and then submit the file. <input type ="file" accept="image/*" id="image" name="i ...

Utilizing ngRepeat to build intricate rows within a table

I have a unique collection that appears as follows: { "10": {}, "12": { "20": { "value": 1, "id": 1, }, "100": { "value": 12, "id": 1, } }, "14": { "10 ...

Position the caret after adding a new element in a content-editable div

I have a contenteditable div that contains various elements. My goal is to automatically create a new paragraph tag right after the element where the cursor is positioned when the user presses the enter key. Currently, I am able to insert the paragraph tag ...

Whenever I clear the contents of the datatable, I notice that 2 thead elements

I am facing an issue with a table that I populate using jQuery's .append() function and then initialize it as a datatable. Since the data is not fetched via an ajax call, I clear both the tbody and thead using .empty(). However, I encounter a problem ...

Next.js application deployment halted due to an unsuccessful completion of the process with the command "/bin/bash -ol pipefail -c npm ci"

After completing the development of a Next.js application (discord clone), I encountered an issue while trying to deploy it on Railway. The error message was: Dockerfile:20 ------------------- 18 | ENV NIXPACKS_PATH /app/node_modules/.bin:$NIXPACKS_P ...

After refreshing the page, vuex is encountering null values when using firebase.auth().onAuthStateChanged

Encountering an issue with Vuex and Firebase Authentication integration. When reloading the page, there is a delay in response from firebase.auth().onAuthStateChanged. I require an immediate response upon page reload without using router guards as seen in ...

AngularJS $log - display line numbers

When using angularjs $log in chrome, it displays the line as: angular.js:9037. I'm looking to have the line number where I actually call this method shown instead. (Displaying my js name and the correct line). Is there a way to achieve this since Angu ...

Adjust the class attribute in real-time

My image doesn't appear in the correct position when I dynamically set it using the margin-top. Below is an image with a red arrow pointing to the right, which is what I want: https://i.stack.imgur.com/ue4mY.png The CSS I have is as follows: .file ...

Ways to extract information from a dynamically generated table

I'm facing an issue with retrieving data from a dynamically generated table within my script... Here is the code snippet: $('#update_panel').html('Loading Date....'); $.ajax({ url: '/Home/GetCountries', type: & ...

Connect-busboy causing NodeJS issue: TypeError - the method 'on' cannot be called on an undefined object

Recently I encountered an issue with a piece of my code: router.route("/post") .get(function(req, res) { // ... }) .post(authReq, function(req, res) { // ... // Get uploaded file var fstream; req.pipe(re ...

Include a CSS file from an external JavaScript file

Is there a way to include an external CSS file in an external JS file? I am trying to reference and load Default.css inside Common.js like the image below shows. Any suggestions are greatly appreciated! BB ...

What is the best way to calculate the number of squares required to completely fill a browser window in real-time?

I am creating a unique design with colorful squares to cover the entire browser window (for example, 20px by 20px repeated both horizontally and vertically). Each square corresponds to one of 100 different colors, which links to a relevant blog post about ...