Achieving functionality with Twitter Bootstrap's "Tabs" Javascript in a Ruby on Rails application

Encountering a JavaScript issue within a Rails application.

Although Twitter's documentation is very clear, I'm still struggling to make dynamic tabs work (tab switching and dropdown). I even went ahead and copied their source code, downloaded their JavaScript files and incorporated them into my application.js file in my Rails app. Can't seem to figure out what I'm doing wrong.

Here's the HTML snippet:

<script>
  $(function () {
    $('#.tabs').bind('change', function (e) {
      e.target // activated tab
      e.relatedTarget // previous tab
    })
</script>
<h3>Demo</h3>
<ul class="tabs" data-tabs="tabs">
<li class="active"><a href="#home">Home</a></li>
<li><a href="#profile">Profile</a></li>
<li><a href="#messages">Messages</a></li>
<li><a href="#settings">Settings</a></li>
<li class="dropdown" data-dropdown="dropdown">
  <a href="#" class="dropdown-toggle">Dropdown</a>
  <ul class="dropdown-menu">
  <li><a href="#fat">@fat</a></li>
  <li><a href="#mdo">@mdo</a></li>
  </ul>
</li>
</ul>
<div id="my-tab-content" class="tab-content">
  <div class="active tab-pane" id="home">
    <p>Lorem Ipsum.</p>

The content of Application.js file is as follows:

// Your custom JavaScript functions and classes go here
// This file gets automatically included using javascript_include_tag :defaults
$(document).ready(function(){

!function( $ ){

  "use strict"

  function activate(element, container) {
    container
      .find('> .active')
      .removeClass('active')
      .find('> .dropdown-menu > .active')
      .removeClass('active')

    element.addClass('active')

    if (element.parent('.dropdown-menu')) {
      element.closest('li.dropdown').addClass('active')
    }
  }

  function tab(e) {
    var $this = $(this)
      , $ul = $this.closest('ul:not(.dropdown-menu)')
      , href = $this.attr('href')
      , previous
      , $href

    if (/^#\w+/.test(href)) {
      e.preventDefault()

      if ($this.parent('li').hasClass('active')) {
        return
      }

      previous = $ul.find('.active a').last()[0]
      $href = $(href)

      activate($this.parent('li'), $ul)
      activate($href, $href.parent())

      $this.trigger({
        type: 'change'
      , relatedTarget: previous
      })
    }
  }


 /* PLUGIN DEFINITION FOR TABS AND PILLS 
  * ============================ */

  $.fn.tabs = $.fn.pills = function(selector) {
    return this.each(function() {
      $(this).delegate(selector || '.tabs li > a, .pills > li > a', 'click', tab)
    })
  }

  $(document).ready(function() {
    $('body').tabs('ul[data-tabs] li > a, ul[data-pills] > li > a')
  })

}(window.jQuery || window.ender);

});

Answer №1

In order to properly implement bootstrap tabs, you will not need the initial script provided in the documentation unless you require additional functionality beyond the standard setup.

What you will need is to reference the bootstrap stylesheet by adding the following link:

<link rel="stylesheet" href="your_bootstrap_folder/bootstrap.min.css">

In addition, make sure to include the following two scripts (assuming jQuery is already included):

<script type="text/javascript" src="your_bootstrap_folder/js/bootstrap-tabs.js"></script>
<script type="text/javascript" src="your_bootstrap_folder/js/bootstrap-dropdown.js"></script>

Lastly, be sure to call the function using the script below:

<script>
    $(function () {
        $('.tabs').tabs()
    })
</script>

These steps should enable the bootstrap tabs functionality on your website.

EDIT: To ensure correct implementation, here is a complete example:

<!DOCTYPE html>

<html>
<head>
    <title>bootstrap tabs test</title>
    <link rel="stylesheet" href="path_to_bootstrap/bootstrap.min.css">
</head>

<body>
    <ul class="tabs">
        <li class="active"><a href="#">Home</a></li>
        <li><a href="#">Profile</a></li>
        <li><a href="#">Messages</a></li>
        <li><a href="#">Settings</a></li>
        <li><a href="#">Contact</a></li>
        <li data-dropdown="dropdown" class="dropdown">
            <a class="dropdown-toggle" href="#">Dropdown</a>
            <ul class="dropdown-menu">
                <li><a href="#">Secondary link</a></li>
                <li><a href="#">Something else here</a></li>
                <li class="divider"></li>
                <li><a href="#">Another link</a></li>
            </ul>
        </li>
    </ul>
    <script type="text/javascript" src="path_to_jquery/jquery-1.6.1.min.js"></script>
    <script type="text/javascript" src="path_to_bootstrap/js/bootstrap-tabs.js"></script>
    <script type="text/javascript" src="path_to_bootstrap/js/bootstrap-dropdown.js"></script>
    <script>
        $(function () {
            $('.tabs').tabs()
        })
    </script>

</body>
</html>

Answer №2

After opening the javascript console in Chrome, it became clear that my scripts were not loading. This was due to the fact that when using Rails, there is no need to add the "public" folder to the path for javascript loading; only the file name is necessary.

Furthermore, in the application.hmtl.erb file, make sure to include <%= javascript_include_tag 'bootstrap-dropdown.js' %> as the :default option does not load these js files by default.

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

Incorporating a file from a specific directory in AngularJS

Every time I execute /sites/all/themes/theme/js/controller.js $scope.template = 'partials/tpl.html' /sites/all/themes/theme/js/index.html <div ng-include='template'></div> /sites/all/themes/theme/js/partials/tpl.html & ...

The command npm install -g . fails to copy the package

The guidelines from npm's developer documentation suggest ensuring that your package can be installed globally before publishing by executing the command npm install -g .. I am currently working on developing an ES6 Command Line Interface (CLI) packag ...

Exploring the use of a customizable decorator in Typescript for improved typing

Currently, I am in the process of creating TypeScript typings for a JavaScript library. One specific requirement is to define an optional callable decorator: @model class User {} @model() class User {} @model('User') class User {} I attempted ...

Use three.js to drag and drop an obj file

I am currently experimenting with a Three.js example that involves draggable cubes. You can find the example here. My goal is to replace the default internally created cubes with obj files. Here's what I've done so far. I have included an obj m ...

Conceal the HTTP status code alert in the Chrome developer console

Currently, I have set up a REST API using Express and for authentication, cookies are being utilized. To retrieve user information, I make a GET request to an endpoint that either returns the user info if logged in or a 401 (Unauthorized) status code if no ...

Utilizing the bufferGeometry setFromPoints function in conjunction with react-three-fiber

Exploring the functionality of the toLinePath function: const toLinePath = (arrayOfPoints, color = 0x000000) => { const path = new THREE.Path(); const firstPoint = arrayOfPoints[0]; path.moveTo(firstPoint.x, firstPoint.y, firstPoint.z); arrayO ...

Toggling the JQuery toggleClass() function to switch a class on and off (or delete it afterwards

Utilizing an angular directive to display a page with left and right columns using <left-column></left-column> and <right-column></right-column>. Whenever a user clicks on an anchor tag <a href="#target1">Target 1</a>, i ...

Incorrect embeds are dispatched when removing messages per user and term

Recently, I've been delving into the world of JavaScript to develop a custom Purge Command. I took inspiration from a Purge Command written in TypeScript by reconlx for their DJS v13 command handler, and with some tweaks, I managed to make it compatib ...

Generate a unique sequence not functioning

I'm attempting to generate a unique string composed of random characters, similar to the example found at this source. $(document).ready(function(){ $('#randomize').click(function() { var str = ""; var possibleChars = "michaeljo ...

The process of passing parameter values by function in useEffect

Hi everyone, I hope you're all doing well. I'm currently facing an issue with trying to retrieve data from my API using the post method. The problem is that I can't use useEffect in any parameter. So, my workaround is to pass the data throug ...

What is the best way to display various titles on separate cards using an API?

I attempted to display various titles fetched from jsonplaceholder on separate cards using jQuery and JavaScript Below is the HTML section: <div class="album py-5"> <div class="container"> <div class="row" ...

Tips for determining if an item in one array is present in a different array

Looking for a way to disable a button using React code? Take a look at the snippet below: todos.filter(todo => todo.completed === true) .map(todo => todo.id) .includes(this.state.checkedIds) But there's a catch - it always seems to return ...

Enhance the functionality of Javascript by integrating the output from a Python script

Integrating Python Script Results into Javascript Code. I am looking to update my Javascript script with the output from a Python script in the context of a Flask application. Currently, I receive a value from my Python script and I want to pass it to or ...

What is the best way to apply the "active" class to a Bootstrap modal image that is sourced from a database

I have a gallery of thumbnails that are fetched from a database. When you click on a thumbnail, it opens in a modal window. I want to enhance this setup by adding a carousel feature so users can slide through the gallery images. The issue I'm facing i ...

Tips for retrieving a value from an async function called within the .map function in React?

After doing some research, I discovered that async functions return a promise whose result value can be accessed using .then() after the function. This is the reason why it's not rendering properly. My question is: how can I render the actual value fr ...

Having issues as a Node.js novice with error messages

Here is the code I have for a basic node.js application: var http = require('http'); var fs = require('fs'); var path = require('path'); var url = require('url'); var port = process.env.port || 1337; http.createSer ...

What is the best way to refresh a React ES6 component following an AJAX response?

I'm a beginner in React and ES6, trying to create a search field that fetches data as the user types. I want to make an AJAX call using the fetch API when the user types at least 3 characters in the field. When I run the fetch snippet code in the brow ...

Creating or updating JSON files using Node.js

I am currently working with JSON files that contain an array of objects. I am looking to update one of these objects and subsequently update the JSON file by overwriting the old file. I understand that this cannot be achieved using AngularJS, but rather wi ...

Tips for maintaining the immutability of an array containing objects in JavaScript

In my program, I am working on creating a new array based on two arrays named "ideaList" and "endorsements", which are declared globally. To ensure the immutability of ideaList and endorsements since they are used in other parts of the codebase, I have att ...

Developing a tool that generates a custom CSS file

While experimenting with adding CSS rules using JavaScript, I encountered this interesting line of code. I am having trouble understanding how the return statement works and how I can adapt it for my own project. var sheet = function() { var style ...