"The issue of the search form CSS class loading twice and causing placement issues following the completion of the AJAX

I implemented a search form that fetches data from the server and displays it in a div, which is working smoothly. However, when I added an ajaxComplete function to add a class for animating the results, it resulted in unexpected behavior.

Upon entering the first letter in the search box, both the search box and result container shift to the left of the page and back to their original position in a glitchy manner. Although this glitch only occurs after the first letter input, the results seem to toggle between opacity 0 and 1 repeatedly.

Below is the code snippet:

$('.search-box input[type="text"]').on("keyup input", function() {
  var inputVal = $(this).val();
  var resultDropdown = $(this).siblings(".result");

  if (inputVal.length) {
    $.get("backend-search.php", {
      term: inputVal
    }).done(function(data) {
      resultDropdown.html(data);
    });
  } else {
    resultDropdown.empty();
  }

});

//-----------------------tablefade in

$(document).ajaxComplete(function() {
  $('#resulttbl').addClass('fadein');
});
.search-box {
  width: 100%;
  font-size: 1.7vw;
}

.search-box input[type="text"] {
  height: 9%;
  padding: 3% 2% 3% 2%;
  border: 2px solid #d2d2d2;
  font-size: 2vw;
  border-radius: 30px;
  color: #7b7b7b;
}

input:focus {
  outline: none;
}

.result {
  display: block;
  height: 20%;
  width: 90%;
  margin: 0 5% 0 %5;
}

.search-box input[type="text"],
.result {
  width: 100%;
  box-sizing: border-box;
}

#resulttbl {
  //---------this is the table loaded thru ajax
  border-spacing: 40px;
}

input[type="text"]::placeholder {
  color: #7b7b7b;
}

@keyframes fadein {
  from {
    opacity: 0;
    margin-top: 0%;
  }
  to {
    opacity: 1;
    margin-top: 1.5%;
  }
}

.fadein {
  animation-name: fadein;
  animation-duration: 400ms;
  animation-fill-mode: forwards;
  animation-iteration-count: 1;
  animation-timing-function: ease-in;
  box-sizing: border-box;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="search-box">
  <input type="text" autocomplete="off" placeholder="Please search by Name, State, or Specialty..." />
  <div class="result"></div>
</div>

Answer №1

If you make a few tweaks to the snippet you provided, the issue could be resolved.

JS Fix: Refer to the jQuery Promise documentation and observe the final example. The code snippet below demonstrates the use of the same concept to append the class fadein after the completion of the resultDropdown.html() method which generates HTML content from the AJAX response.

CSS Adjustments: modified

.result {
  display: block;
  ...

to

.result {
  display: none;
  ...

and included

.fadein {  
  ... 
  display: block !important;
}

$('.search-box input[type="text"]').on("keyup input", function() {
  var inputVal = $(this).val();
  var resultDropdown = $(this).siblings(".result");

  if (inputVal.length) {
    $.get("backend-search.php", {
      term: inputVal
    }).done(function(data) {
           $.when( resultDropdown.html(data); ).done(function() {
               $('#resulttbl').addClass('fadein');
           });          
    });
  } else {
    resultDropdown.empty();
  }

});

//-----------------------tablefade in
.search-box {
  width: 100%;
  font-size: 1.7vw;
}

.search-box input[type="text"] {
  height: 9%;
  padding: 3% 2% 3% 2%;
  border: 2px solid #d2d2d2;
  font-size: 2vw;
  border-radius: 30px;
  color: #7b7b7b;
}

input:focus {
  outline: none;
}

.result {
  display: none;
  height: 20%;
  width: 90%;
  margin: 0 5% 0 %5;
  box-sizing: border-box;
}

.search-box input[type="text"] {
  width: 100%;
  box-sizing: border-box;
}

#resulttbl {
  //---------this is the table loaded thru ajax
  border-spacing: 40px;
}

input[type="text"]::placeholder {
  color: #7b7b7b;
}

@keyframes fadein {
  from {
    opacity: 0;
    margin-top: 0%;
  }
  to {
    opacity: 1;
    margin-top: 1.5%;
  }
}

.fadein {
  animation-name: fadein;
  animation-duration: 400ms;
  animation-fill-mode: forwards;
  animation-iteration-count: 1;
  animation-timing-function: ease-in;
  box-sizing: border-box;
  display: block !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="search-box">
  <input type="text" autocomplete="off" placeholder="Please search by Name, State, or Specialty..." />
  <div class="result"></div>
</div>

For a more comprehensive solution, it would be helpful if you could share the code for resultDropdown.html() and resultDropdown.empty() methods along with a sample of the data returned from the server.

Answer №2

Big thanks to everyone for your assistance! Apologies for the delay in responding, my day job kept me busy -.-

There were a couple of issues I encountered. One was due to my own oversight, and the other... well, let's just say I had a moment of ignorance. The margins for the "result" class were mistakenly set to %5, causing some strange behavior. Additionally, nesting the "result" class within the "search-box" class resulted in the animation playing twice. I was simply following a tutorial without considering the consequences... To make matters worse, during my attempts to troubleshoot, I neglected to clear my cache because I didn't realize its importance 0.o

Thanks once again to everyone:)) Hopefully, I'll soon be able to showcase some live examples with PHP once I can get myself a little piece of the internet!

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

Display Particular Array Pictures in Popup Utilizing Laravel and jQuery AJAX

I am struggling to display a specific image from an array of images. Here is what I've attempted: Array Images Controller public function edit($id) { $product = \App\Product::find($id); $picts = []; foreach (json_decode($produ ...

Django template experiences issue with AJAX functionality when attempting to open a new window through right-click action

I have successfully created a link using AJAX with the following HTML code: <a id="post_click" href="{{ post.online_url}}" rel="nofollow"> <button class="w-100 " type="button" name="button& ...

Despite implementing desandro and new jQuery, the tumblr masonry + infinite scrolling feature still causes posts to overlap on the

Hi there, I am relatively new to the world of javascript and currently facing a frustrating issue with masonry and infinite scroll on my Tumblr blog. I have scoured through various forum discussions regarding these problems but unfortunately, none of the s ...

Insert a picture into a table using the ajax response in Laravel

When attempting to add an image to a table, I am encountering an issue where the src path is not displaying any results. if(data ){ txt += '<tr><td>'+data.groupname[i].group_name+'</td><td class="text-right"&g ...

The submission directed me to the PHP webpage

Trying to integrate AJAX and jQuery into my code has been a challenge. Whenever the form is submitted, it redirects me to the PHP page in the action attribute. I'm not sure why this keeps happening, and I've been struggling to figure it out. The ...

What is the best way to ensure that my drop-down menu items match the size of the parent nav bar?

I'm having trouble creating a dropdown menu using only CSS. Specifically, I am struggling to ensure that the dropdown menu is the same size (width and height) as its parent element. Here is a link to a working example: HERE This is the snippet of HT ...

Is there a way to showcase the string message from BadRequest(message) utilizing Ajax?

I am currently working on implementing an API Controller. public ActionResult<Campaigns> AddCampaign([Bind("Name, Venue, AssignedTo, StartedOn, CompletedOn")] Campaigns campaigns) { try { if (ModelState.IsVal ...

Enhancing FileUpload functionality in ASP.NET with jQuery function prior to postback

My webpage is built with .aspx and contains the following code: .. <form id="frm" runat="server"> <asp:FileUpload runat="server" id="fileupload" onchange="browsed()" /> <asp:Button runat="server" OnClick="Upload_Click" id="uploadb ...

Enabling element overlap using jQuery

I have implemented jQuery to animate a navbar button on one of my web pages. However, the animation causes the div below it to be displaced and disrupts the layout. Is there a way to allow the button to animate without affecting the position or layout of t ...

What's the reason the element inside the <div> is not displayed when a value is selected in the dropdown box?

I am perplexed as to why the element inside the does not appear when a value is selected in the drop down box. However, it works perfectly fine in JSFiddle: JSFiddle Below is my HTML code and Jquery script that functions properly in my own system: <t ...

When the settings are saved in PHP and AJAX, the password fields are automatically cleared

On my settings page, users can update their information. All fields are working correctly except for the password field. Currently, when a user clicks submit, it updates the password to nothing in the MySQL database. What I want is for nothing to happen in ...

Outlook for Windows automatically sets the default font for HTML emails to Times New Roman

My email design looks great in Mac Outlook, but Windows Outlook is changing the font to Times New Roman. Below is the code for the email template. Can someone help me figure out what I'm missing? <style style="-ms-text-size-adjust: 100%;&q ...

We are hosting an event focused on DOM text selection outside of Input or TextArea elements

I need help finding a Javascript event that triggers when a user highlights paragraph text with their mouse on a web page. Once the text is highlighted, I want to access it using window.getSelection(). Just to clarify, I am not looking for ways to capture ...

The sequence of events in the DOM for jQuery droppable interactions

Running into a dilemma with my listeners. One is the droppable class from jquery UI $("#myDiv").droppable({ drop: function( event, ui ) { console.log('Triggered!'); if (window.draggingMove == true) { alert(&ap ...

Tips for keeping the header section anchored to the top of the page

I am having trouble getting the menu bar and logo to stick at the top of my header section in the template. I have been trying different solutions, including using the sticky.js plugin for almost 4 days now but it's not working. I also have parallax e ...

When using jQuery's `text()` function, the `<br>` element is interpreted as a

When trying to retrieve an element from the DOM like this $('#id').content().text(); An issue arises when the element contains: <p>Hello</p> <p><br></p> <p>World</p> In HTML, it would look like: Hell ...

Learn how to reposition the mat-option easily

I have an angular app with an autocomplete field that I need to adjust the position of. I have consulted the official documentation under the method updatePosition, which states: "Updates the position of the autocomplete suggestion panel to ensure that it ...

Having trouble with parsing JSON data using jQuery?

I am currently working on retrieving a result set using postcodes with jQuery autocomplete. However, the code I have implemented seems to be displaying an empty set of rows. <html lang="en"> <head> <meta charset="utf-8> <title>Ausp ...

Revise website design to adjust dynamically according to screen dimensions

Currently, I am working on a school project with a website created by former students. Unfortunately, I have limited knowledge of HTML and CSS which has made it challenging for me to ensure the site is mobile-friendly. There are issues such as text overflo ...

Enhance your Datatables experience with the inclusion of a select form

Here is the code I am working with: Javascript: $(document).ready(function() { $('#example').DataTable( { "ajax": '../ajax/data/arrays.txt' } ); } ); HTML <select id="office-select" name="idOffice"> <op ...