Using jQuery UI to trigger Highlight/Error animations

Apologies if this question seems obvious, but I can't seem to find a clear answer anywhere...

Is there a way to add a highlight/error message similar to the ones on the bottom right of this page: http://jqueryui.com/themeroller/ by simply using a jQuery UI function?

I've looked at the source code but it's not immediately obvious. Do they manually input the HTML for this?

Thank you

----------------------------------------- SOLUTION ---------------------------------------

jQuery: (create a new file called whatever.js and add the following code)

$(document).ready(function(){

if($("div.error")[0]){
    createError($("div.error"));
}

if($("div.notice")[0]){
    createHighlight($("div.notice"));
}
});

//functions start
function createHighlight(obj){
    obj.addClass('ui-state-highlight ui-corner-all');
    obj.html('<p><span class="ui-icon ui-icon-alert" style="float: left; margin-right:.3em;"></span>'+obj.html()+'</p>');
}

function createError(obj){
    obj.addClass('ui-state-error ui-corner-all');
    obj.html('<p><span class="ui-icon ui-icon-alert" style="float: left; margin-right:.3em;"></span>'+obj.html()+'</p>');
}

HTML: Simply create divs where you want to display the messages like:

<div class="error"><b>ERROR:</b> The message goes here</div>

or for Notices:

<div class="notice"><b>NOTICE:</b> The message goes here</div>

You can then customize the appearance of these classes using CSS.

I hope this is helpful to someone.

----------------------------------------- SOLUTION ---------------------------------------

Answer №1

While there isn't a specific jQuery UI function for displaying errors on a page, you can still add an error class to elements using jQuery like so:

$('#element').addClass('ui-state-error ui-corner-all'); // Adds rounded corners
$('#element').addClass('ui-state-error'); // Adds squared corners

I trust this information is useful!

Answer №2

As per the guidelines provided, once Jquery UI css is loaded, you have access to a variety of classes for customization:

http://jqueryui.com/docs/Theming/API

For instance, the alert box can be styled in the following manner:

<div class="ui-state-error ui-corner-all" style="padding: 0 .7em;">
  <p>
    <span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>
    <strong>Alert:</strong>
     Sample ui-state-error style.
  </p>
</div>

Answer №3

Expanding on Guillaume's explanation, I devised a set of jQuery plugins that can transform a standard element into either a jQuery UI error or highlight element.

const defaultOptions = { noCorners: false };

function applyErrorHighlight($element, options) {
  const opts = $.extend(defaultOptions, options);
  const type = opts.type;
  let icon = opts.icon;
  if (!icon) {
    icon = type === 'highlight' ? 'ui-icon-info' : 'ui-icon-alert';
  }
  return $element.each(function() {
    const $self = $(this);
    const $wrapper = $('<div>')
      .addClass('ui-widget')
      .append($('<div>')
        .addClass(['ui-state-' + type, !opts.noCorners ? 'ui-corner-all' : ''])
        .append($('<p>'));
    $self.wrap($wrapper);
    $self.closest('p').prepend($('<span>').addClass(['ui-icon', icon]));
    $self.children().unwrap();
  });
}

(function($) {
  $.fn.error = function(options) {
    applyErrorHighlight(this, $.extend({ type: 'error' }, options));
  };
  $.fn.highlight = function(options) {
    applyErrorHighlight(this, $.extend({ type: 'highlight' }, options));
  };
})(jQuery);


$('.error').error();
$('.highlight').highlight({ icon: 'ui-icon-star', noCorners: true });
.ui-widget {
  margin-bottom: 1em;
}

.ui-widget>div {
  padding: 0 0.7em;
}

.ui-widget>div>p>.ui-icon {
  float: left;
  margin-right: .3em;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/themes/base/jquery-ui.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
<!-- Error -->
<div class="ui-widget">
  <div class="ui-state-error ui-corner-all">
    <p>
      <span class="ui-icon ui-icon-alert"></span>
      <strong>Alert:</strong> Sample ui-state-error style.
    </p>
  </div>
</div>
<!-- Highlight -->
<div class="ui-widget">
  <div class="ui-state-highlight ui-corner-all">
    <p>
      <span class="ui-icon ui-icon-info"></span>
      <strong>Hey!</strong> Sample ui-state-highlight style.
    </p>
  </div>
</div>
<!-- jQuery plugin -->
<div class="error"><strong>Alert:</strong> Sample ui-state-error style.</div>
<div class="highlight"><strong>Hey!</strong> Sample ui-state-highlight style.</div>

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

Modifying elements within a JSON array-generated list

As a beginner in JavaScript, I have encountered an issue with my code. It dynamically creates a list from a JSON array called rolesData and displays the data from "roles" in a list based on a random selection (using document.body.appendChild(createList(rol ...

Having trouble getting CSS hover to work on hidden elements?

I am having trouble getting the rollover effect to work correctly on this page, and I can't seem to figure out what's causing the issue. My CSS is quite basic: open{visibility:hidden;} open:hover{visibility:visible;} If you would like to take ...

What is the best method to dynamically assign a class to a TD element in a data table when adding

I am looking to apply a class to the td element when receiving data from an ajax call Here is the default HTML code snippet <tr> <td>@fisrt.System_Code.Code</td> <td>@fisrt.System_Code. ...

Managing exceptions triggered by jQuery's Ajax function

Within my webpage, I am utilizing a jQuery ajax function to connect with a basic Webservice. This Webservice retrieves data from a database and then binds it to various controls on the page. The ajax function is triggered by the onchange event of a select ...

I am having trouble properly positioning an icon next to its corresponding text within a menu item

I'm a newcomer to the world of HTML5 + CSS3 and I'm having trouble with aligning menus, text, and icons within the menu. Here's the issue: Each line of the menu consists of an icon and a text description. The problem is that they are too clo ...

Ensuring data validity in Angular 2 before enabling a checkbox

In my form, there is a checkbox for admins to edit user accounts. Each user object includes a boolean value isAdmin. I am trying to prevent users from editing their own account while still allowing them to view the values. However, no matter what I try, I ...

Ensure that data is accurately confirmed using an alternative mode within react-hook-form

Currently utilizing react-hook-form with the primary validation mode set to "onChange": const formMethods = useForm({ mode: 'onChange' }) I am looking to modify the mode property for a specific input nested within a Controller, but I am unsure ...

Sliding panel, perhaps?

I've been working on a small project and I've managed to create this panel, but I'm looking to change the position of the "tab" to something similar to this Can anyone help me out? I'm still new to all of this~ http://jsfiddle.net/ ...

Counting with Jquery and managing variables inside square brackets

When a form containing a hidden field is loaded, <input type = "hidden" class = "counter" value="6"> I utilize Jquery in my code: var counter = $(".counter:last").val() After that, a row with a text field is added when a click event occurs: .app ...

Acquiring the index of a selector event within a list of dynamic elements

I am seeking guidance on how to go about solving the issue of obtaining an event index. I have a hunch that closures might play a role in the solution and would appreciate some insights. Initially, I dynamically build an HTML5 video container using an aja ...

Can the parent's :active pseudo class be overridden?

I'm struggling with changing the color of a div when clicked while preventing its parent's pseudo-class from triggering. Here is the markup I have: <div class="parent"> I should change my color to green when clicked <div class="elem ...

CSS grid is organizing itself neatly on larger screens

I'm currently facing an issue with displaying a CSS grid on my page. When viewed on desktop, the grid appears stacked up instead of in separate columns. I've tried various methods like dividing it into 4 columns and using spans for width but noth ...

Dealing with Angular.js $http intercept error "net::ERR_CONNECTION_REFUSED"

Currently, I am attempting to create a universal error handler for my website utilizing $http interceptors. However, it seems that the interceptors are not functioning as intended. I have set up interceptors for 'response' and 'responseErro ...

Positioning oversized images in a React Native application

Looking to showcase two images side by side using React Native, where I can customize the screen percentage each image takes up. The combined size of the images will exceed the horizontal screen space available, so I want them to maintain their original di ...

What is the best way to display an international phone number using Angular Material V6?

I've been working on a project that utilizes Angular Material V6. My goal is to display international phone numbers with flags in a Material component text box. After some research online, I came across an npm module that achieved this but it was tail ...

Is it possible for me to load a window following a click

I developed a customized Modal Box that functions similar to the browser's "alert()". When using the traditional alert(), it halts the rendering and executions of the underlying webpage. I am seeking methods to achieve this same behavior: preventing ...

Invoke a Java script function for Regular Expression validation failure in ASP.NET

I have a <asp:RegularExpressionValidator> that validates a text box, and I also have a JavaScript function that prevents entering non-numerical values in the textbox. When I use the expression validator alone, it works fine. However, as soon as I add ...

Collecting information from form submissions, accessing data from the database, and displaying the results

I am currently working on a project using nodejs, express, and mongodb within the cloud9 IDE. My goal is to create a page with a form that allows users to input data, search for corresponding information in the database, and display that data on the same ...

Creating TypeScript models from a JSON response in React components

My Angular 2 application retrieves a JSON string, and I am looking to map its values to a model. According to my understanding, a TypeScript model file is used to assist in mapping an HTTP Get response to an object - in this case, a class named 'Custo ...

Using Vue3 to Enable or Disable the Submit Button Based on Changes in Editable Form Content

Here is a practical example, demonstrating how to create an editable address form. The save button should remain disabled if the form remains unchanged, as there is no need to submit it. However, when a value changes, the save button should become enabled ...