Creating a dynamic button with Angular that appears when focused

I want to have a button appear when the user focuses on an input with the ng-model=query. I know there is an ng-focus directive, but how can I implement it?

  <input type="search" ng-model="query">

  <!--this is the button I need to show once the user focus the input-->
  <div ng-show="query.length"
       ng-click="query = ''">
      Cancel
  </div>

This is the button that should display when the user focuses on the input. Instead of using ng-show, what alternative could I consider?

Answer №1

If you're looking to implement this functionality using pure angular, the code would appear as follows:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>

  <input 
  type="search" 
  ng-model="query" 
  ng-focus="isSearchFocused=true"
  ng-blur="isSearchFocused=false"/>

<div 
  style="opacity:{{isSearchFocused && query.length?1:0}}"
  ng-click="query = ''">
  Cancel
</div>
 
</div>

Answer №2

If you want to break away from pure AngularJS and utilize CSS instead for a particular action, there are several approaches you can take. One effective method is using the plus (+) selector as shown below:

HTML

<input type="search" ng-model="query">

<!--this is the button I need to show once the user focus the input-->
<div class="hidden_btn" ng-show="query.length" ng-click="query = ''">
    Cancel
</div>

CSS

.hidden_btn { /* Hide this button initially */
    display: none;
}
input[ng-model="query"]:focus + .hidden_btn {
    display: block;
}

There are alternative ways to achieve this functionality, which can be found in the following link: AngularJS: show hide elements based on mouse events. These techniques can not only be applied to your specific ng-model selector but also to similar methodologies within AngularJS.

If you have any queries, feel free to ask!

Answer №3

To select adjacent siblings, use the + selector.

div.dat_div {
    display: none;
}
input[ng-model="query"]:focus + div.dat_div {
    display:block;
}
<input type="search" ng-model="query">
 <!--this is the button I need to show once the user focus the input-->
<div class="dat_div" ng-show="query.length" ng-click="query = ''">
    Cancel
</div>

In jQuery:

$('input[ng-model="query"]').on('focus',function(){$('div.dat_div').show();});

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 locating an element beyond the page source with Puppeteer

My goal is to extract specific information from a webpage by utilizing this code snippet to target an element and retrieve certain values within it: const puppeteer = require('puppeteer'); function run (numberOfPages) { return new Promise(a ...

Error encountered while using Google Translate with XMLHttpRequest (Missing 'Access-Control-Allow-Origin' header)

Trying to access a page that utilizes Google Translate is resulting in the following error: XMLHttpRequest cannot load http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit. No 'Access-Control-Allow-Origin' heade ...

Expanding the height of Bootstrap 4 cards

I'm having an issue with Bootstrap 4's card columns where the height of the shorter card ends up stretching to match the one beside it. This only occurs when I add the 'row' class to the parent div. If I remove the 'row' class ...

Is there a way to transmit a div using Node.js?

Scenario: I am developing a web application that allows users to draw on a canvas, save the drawing as an image, and share it with others using Node.js. Current Progress: Drawing functionality (real-time updates on both clients). Saving the canvas as a ...

Transform Django Model Instance from Serialized Back to Object using Ajax

Currently, I'm utilizing Ajax to search for a model instance. Once found, I return that instance and pass it as a variable to a template tag within my template. To achieve this, in my view, I serialize the object before sending it to the Ajax success ...

React Scroll and Material-UI button active link not functioning correctly

Whenever the link goes to the correct page, I want to add a special background effect or change the font color. Despite trying to use CSS for this purpose, it didn't work as intended. If you want to take a look at my code on codesandbox, follow this ...

Trouble with implementing a stationary header for a table on IE9?

I have successfully created a table with a fixed header and scrollable content. I utilized CSS classes "fixedHeader" for thead and "scrollContent" for tbody: thead.fixedHeader tr { position: relative; } html > body thead.fixedHeader tr { displa ...

Can I modify a property in DataTables.Net using the data itself?

I am trying to set the "column" property based on the ajax data that I receive. The json data contains a "data" and "columns" property, so in order to extract the data, my code would look something like this: primaryTable = $('#example').DataTa ...

Challenges with CSS div styling (border and image issues)

I won't bore you with the details, but I'm trying to overlay image links on top of a background image in specific positions. Despite my best efforts, the images are not changing no matter how much I tweak their parameters. Here is the HTML code: ...

Retrieving the input[text] value in TypeScript before trimming any special characters

One of the tasks I am working on involves a form where users can input text that may contain special characters such as \n, \t, and so on. My objective is to replace these special characters and then update the value of the input field accordingl ...

Guide on presenting an image retrieved from a database with ajax

I am currently developing a straightforward mobile application that utilizes a database to store various types of content, including images. I have implemented ajax requests to retrieve this information and display it within the app. However, I am encounte ...

Issues encountered with the data-binding functionality of angular-froala 2.1.0 when used in conjunction with angular 1.1

At the moment, I'm immersed in a project that utilizes Angular 1.1.5. Unfortunately, upgrading Angular is off the table for now. Our goal is to integrate a feature-rich HTML5 WYSIWYG-editor, and we've settled on trying out Froala because it alig ...

"Seamlessly Integrating AngularJS with WebGL for Stunning Canvas Inter

I am new to AngularJS and curious about its compatibility with HTML5 Canvas or WebGL. Are there any tutorials available on how to integrate AngularJS into a view that uses these technologies? I have noticed some games claiming to be developed with Angular ...

Can we enhance the efficiency of this equation?

The formula provided organizes the elements in the container based on mouse movement. The issue stemmed from the image size and the different calculations performed when approaching along the x and y axes from various directions. const zoomEffect = (even ...

How can I send a file and a string request using the POST method to a Spring REST controller that accepts byte[] and Strings with Angular

Need help with sending a post method that includes a file and another string request parameter to a spring rest controller using angular. The server controller parameter is set up to receive an array of bytes for the file and another string request wrappe ...

What is the best way to extract text/html that appears between two consecutive <input> tags?

Is there a straightforward method to extract the text or HTML content located between input tags, even though these tags do not require closing tags? For instance, in the example below, I am looking to retrieve <b>Bob and Tim</b><br>Tim & ...

Are there any methods to improve the coding, align images to the center, and ensure that elements stay in their designated positions?

Is there a way to tidy up the code, center images, and keep everything in place? This is the look I desire: The main outer box should remain centered on the browser page. Pause, play, and stop buttons should float to the left of the box. My image sh ...

What steps can I take to make sure a jQuery Mobile table does not become responsive?

My goal is to make a table responsive by using media queries to hide optional columns on smaller devices. I need to hide two columns based on different screen sizes: @media screen and (max-width: 33em) { th.optional-1, td.optional-1 { display: no ...

Issue: missing proper invocation of `next` after an `await` in a `catch`

I had a simple route that was functioning well until I refactored it using catch. Suddenly, it stopped working and threw an UnhandledPromiseRejectionWarning: router.get('/', async (req, res, next) => { const allEmployees = await employees.fi ...

Add numerous submit buttons within a form. Upon clicking on a button, the form should be submitted to a specific URL using AJAX

I have a form with two submit buttons: one labeled as "SUBMIT" and the other as "SCHEDULE NEXT ROUND". When a user clicks on the "SUBMIT" button, the form values should be stored in the database and redirect to the view page. If they click on the "SCHEDULE ...