Customizing the appearance of the Bootstrap Typeahead

I've been experimenting with the Bootstrap Typeahead for my search feature. I successfully implemented the dropdown list using Ajax. However, I am looking to customize the width, padding, and background color of the dropdown menu, which is currently white. How can I make these adjustments?

Additionally, I want to make sure that a "View All Results" option always appears at the end of the dropdown. Clicking on this option should redirect the user to the search results page.

While I have managed to add this functionality, I am struggling to change the appearance of the dropdown menu. I also want to ensure that the "View All Results" option remains consistent regardless of the search query and does not highlight matching characters.

What steps can I take to achieve these customizations as shown in the current result below?

Your assistance in altering the look of the dropdown would be greatly appreciated.

Answer №1

To easily change the appearance of the dropdown, you can follow the suggestion in the previous answer by adding custom styles in a file that comes after Bootstrap CSS. To identify which selectors to use for overriding Bootstrap's styles, it is recommended to utilize your browser's DOM inspection tools.

Adding a custom link at the end of the results poses a challenge. One approach is to append an item to the results array at the beginning of the render function. This particular function seems ideal because unlike the sorter, it is called after the array is sliced at the maximum number of items set in the options. However, since render cannot be configured with plugin options, a manual override is necessary:

$('input').typeahead().data('typeahead').render = function (items) {
      var that = this
      items.push('View All'); // Add "View All" option

      // Default render function taken from Bootstrap's JS source
      items = $(items).map(function (i, item) {
        i = $(that.options.item).attr('data-value', item)
        i.find('a').html(that.highlighter(item))
        return i[0]
      })

      items.first().addClass('active')
      this.$menu.html(items)
      return this
    };

To prevent the custom link from being highlighted as users type, customization of the default highlighter function is required:

highlighter: function (item) {
    if (item == 'View All') 
        return '<strong>' + item + '</strong>'

    // Default highlighter function taken from Bootstrap's JS source
    var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
    return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
        return '<strong>' + match + '</strong>'
    });
}

To handle clicks on the custom link, an updater function needs to be implemented whenever an option from the dropdown is selected:

updater:function(item){
    if(item == 'View All'){
        window.location = 'http://example.com/search?q=' + this.$element.val();
    }
    return item;
}

A complete working example can be found in this fiddle

Answer №2

If you want to customize the appearance of the Typeahead menu, you can do so by adding a custom CSS file.

.typeahead{
    background-color: #fff;
    min-width: 250px;
}

.typeahead li{
    padding: 5px;
}

.typeahead li.active{
    background-color: #eee;
}

Remember to place your custom style sheet after the bootstrap.css file for it to take effect.

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

Show a pop-up notification when the mouse passes over a word in the text

I've been grappling with this issue for days now and could really use some guidance. Despite scouring the web, I'm unsure if I've approached it correctly. What I'm trying to achieve is having an alert box pop up each time a user hovers ...

Determine the body's height by adding the heights of the header and footer

In my design, there is a header with a height of 8rem; .header { top: 0; left: 0; height: 8rem; } Following that, there is a footer with a height of 5rem; footer { width:100%; height: 5rem; } I am attempting to calculate the heig ...

Changing the Material UI imported Icon on click - a step-by-step guide

Hey there, I'm currently working with React JS and Redux. I have a challenge where I need to change the star outline icon to a filled star icon on click. The icon is located just after emailRow in the emailRow__options section. Can someone assist me w ...

Having difficulty drawing an arrow connecting one mesh object to the surface of another mesh object

When attempting to draw an arrow from one mesh object to another, I encountered some issues. Directly using the positions of the objects as arguments in the Arrow Helper resulted in the arrow going inside the object due to the position representing the cen ...

Repeated tweets detected within real-time Twitter stream

I've been working on developing a live update Twitter feature, but I've noticed that it sometimes duplicates tweets and behaves erratically. Did I make a mistake somewhere in my code? http://jsfiddle.net/JmZCE/1/ Thank you in advance (note: I p ...

Ensure to verify the dimensions and size of the image prior to uploading

Is there a way to check the dimensions of an image using this function? I want to verify it before uploading... $("#LINK_UPLOAD_PHOTO").submit(function () { var form = $(this); form.ajaxSubmit({ url: SITE_URL + 'functions/_app/execute ...

Retrieve hyperlinks from webpage

Currently, I am attempting to extract all Netflix movie/show links from this source , along with their respective country names. For example, I aim to retrieve information such as , USA, etc. Despite my efforts so far, the current code retrieves all links ...

When working with JavaScript, it's important to note that any reference used outside of the catch block

Our JavaScript code includes a try...catch block that functions as follows: We import the customFile using: const ourCustomClassFile = require('./customFile'); In the customFile.js file, we have defined a function const sendErrorNotification ...

When attempting to execute "nodemon," the command was not detected

When trying to use 'nodemon' in the command line, an error occurs stating that it is not recognized as a cmdlet, function, script file, or operable program. The system suggests checking the spelling of the name and verifying that the path is corr ...

Utilizing AngularJS to selectively filter objects based on specific fields using the OR operator

My collection includes various items with different attributes. For instance, here is the information for one item: {"id":7,"name":"ItemName","status":"Active","statusFrom":"2016-01-04T00:00:00","development":"Started","devStartedFrom":"2016-01-04T00:00:0 ...

What is the best way to make the current year the default selection in my Select control within Reactive Forms?

Hey there! I managed to create a select element that displays the current year, 5 years from the past, and 3 years from the future. But now I need to figure out how to make the current year the default selection using Reactive Forms. Any ideas on how to ac ...

What could be causing the issue where Ruby on Rails date picker isn't updating the database? Any suggestions for troubleshooting

On my checkout page, I want to incorporate a form with 3 delivery choices using a date picker. Although I have successfully implemented the form on the page by using code from another site, I am facing an issue where the selected dates are not being store ...

Filter items by nested properties in ngRepeat

Is it possible to filter a complex object with nested properties using the ng-repeat filter? Can we achieve this filtering with the ng-repeat filter provided out of the box? Data { Name: 'John Smith', Manager: { id: 123, Name: &a ...

Dimension of images within bootstrap column division

I have a layout with three columns using col-md-4 for a thumbnail design, and then I have another page with col-md-8. In both cases, I need to display an image. Should I use the same image for both layouts or would it be best to have two separate images, e ...

Jquery-ajax fails to accomplish its task

I am just starting to learn about ajax and recently created a simple page on my local server to practice sending and receiving data from/to a JSON file in the same directory. Although the GET method is working perfectly fine, I am having trouble understan ...

VueJS in collaboration with Quasar framework

Incorporating VueJS with Quasar framework, I created a data table. Here is my implementation: <template> <div class="q-pa-md"> <q-table title="Task List Of The Day" :columns="columns" row-key="name" :pagination ...

Ways to retrieve data from response instead of subscription JSON in Angular 2/4

My Service : retrieveData(url,request) { return this.http.post(this.apiUrl+url,request).subscribe( (response) => {return response.json()} ); } My Component : ngOnInit() { this.data = this.dataService.retrieveData(&apos ...

Storing the ID passed from Next.js/Link into Next.js

I'm encountering some issues with the current flow setup. I have a component ArticleList that listens to articles, and upon clicking on it, redirects you to the individual article page. The redirection is done using next/Link, where the id is passed a ...

Tips for passing variables through onclick to JavaScript file

My task involves querying a database and implementing a filter based on country selection from a map. After writing the JavaScript and PHP code, everything seems to work fine except for one issue - passing a name with an onclick function to initiate the qu ...

Is there a way to configure datetimepicker bootstrap to display the previous month?

Here is my attempt using JavaScript : var lastMonth = new Date(); lastMonth.setMonth(lastMonth.getMonth() - 1 ); $('#datetimepicker').datetimepicker({ defaultDate: lastMonth }); It seems to be functioning correctly. I am curious if there a ...