Bora
Bora

Reputation: 248

JavaScript & JQuery not alphabetizing list on certain devices

What I intend for this code to do:

What happens instead:

The list is alphabetizing on my laptop but not on my iPhone. I also has to change the conditional in the JavaScript because the code kept defaulting to the else case. I'm not grasping exactly what the if statement is doing, so if someone could explain that, I would appreciate it greatly.

JavaScript:

$(document).ready(function (e) {
    var $sort = this;
    var $list = $('div.dropdown-content');
    var $listLi = $('a', $list);
    $listLi.sort(function (a, b) {
        var keyA = $(a).text();
        var keyB = $(b).text();
        if ($($sort).hasClass('asc')) {
            return (keyA > keyB) ? 1 : 0;
        } else {
            return (keyA > keyB) ? 1 : 0;
        }
    });
    $.each($listLi, function (index, row) {
        $list.append(row);
    });
});

HTML (for the relevant area):

<!DOCTYPE html>
<head>
    <title>GeoMaps</title>
    <link rel="stylesheet" type="text/css" href="main.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script type="text/javascript" src="main.js"></script>
</head>

<body>
    <ul class="nav">
        <li class="nav navhome">
            <a href="">
                <h3 style="display:inline">GeoMaps</h3>
                <h6 style="display:inline">for use with AP® Human Geography</h6>
            </a>
        </li>
        <li class="nav" style="float:right"><a href="#maps">About</a></li>
        <li class="dropdown" style="float:right">
            <a href="javascript:void(0)" class="dropbtn">Maps</a>
            <div class="dropdown-content">
               <!--This list will be automatically alphabetized by JS-->
                <a href="#">East Asia</a>
                <a href="#">Oceania</a>
                <a href="#">Russia</a>
                <a href="#">Europe</a>
                <a href="#">South Asia</a>
                <a href="#">Southeast Asia</a>
            </div>
        </li>
    </ul>

This website is hosted on GitHub pages, if that makes a difference.

Upvotes: 1

Views: 43

Answers (1)

guest271314
guest271314

Reputation: 1

Sort by the first character of .textContent of a element

$(function() {
  var $list = $("div.dropdown-content");
  $list.html(
    $("a", $list).sort(function(a, b) {
      return b.textContent[0] < a.textContent[0]
    })
  );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<ul>
<li class="dropdown" style="float:right">
  <a href="javascript:void(0)" class="dropbtn">Maps</a>
  <div class="dropdown-content">
    <!--This list should be automatically alphabetized by JS-->
    <a href="#">East Asia</a>
    <a href="#">Oceania</a>
    <a href="#">Russia</a>
    <a href="#">Europe</a>
    <a href="#">South Asia</a>
    <a href="#">Southeast Asia</a>
  </div>
</li>
</ul>

Upvotes: 1

Related Questions