stephan
stephan

Reputation: 2403

Why is this very basic JS dropdown menu not working?

It works in Codepen, but it doesn't work locally. I have the html, css, js files in the same directory and I am importing them as you can see in the html snippet. It has been suggested that my path to the js file may be incorrect, but the js file is in the same directory as everything else and I can call my cs file in the same manner and that works.

The only thing I can think of here is I'm importing the incorrect jquery and jquery ui files that my menuscript requires?

So my question is why does this example work here http://codepen.io/WhiteWolfWizard/pen/DwKjc, but not on my local machine?

HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="menuscript.js"></script>
<div class='dropdown'>
  <h1 class='title'>Select</h1>
  <ol class='drop'>
    <li>Apple</li>
    <li>Orange</li>
    <li>Banana</li>
    <li>Pineapple</li>
    <li>Mango</li>
  </ol>
</div>

CSS

.dropdown {
  position: relative;
  margin: 50px auto;
  display: table;
  font-family: sans-serif;
  font-size: 11pt;
  color: #FC3;
  line-height: normal;
  text-align: left;
  font-smoothing: antialiased;
}
.dropdown .title {
  cursor: pointer;
  height: 45px;
  padding: 0 20px;
  border-radius: 5px;
  display: block;
  box-shadow: 0 0 0 1px #FC3;
  line-height: 45px;
}
.dropdown .title:after {
  content: '';
  float: right;
  width: 0;
  height: 0;
  margin: 20px 0 0 20px;
  border-width: 5px 4px 0;
  border-style: solid;
  border-color: #FC3 transparent transparent transparent;
}
.dropdown .drop {
  position: relative;
  top: 100%;
  margin-top: 1px;
  border-radius: 0 0 5px 5px;
  display: none;
  overflow: hidden;
  box-shadow: 0 0 0 1px #FC3;
}
.dropdown .drop li {
  cursor: pointer;
  padding: 10px;
}
.dropdown .drop li:hover {
  background: #FC3;
  color: #FFF;
}

.select .title {
  border-radius: 5px 5px 0 0;
}
.select .title:after {
  transform: rotate(180deg);
}

JS

$('.dropdown .title').on('click',function(){
  $(this).parent().toggleClass('select').find('.drop').toggle();
});
$('.dropdown .drop li').on('click',function(){
  var $this = $(this), input = $this.text();
  $('.dropdown .title').text(input);
});
    enter code here

http://codepen.io/WhiteWolfWizard/pen/DwKjc

Upvotes: 0

Views: 66

Answers (1)

Nicolas Straub
Nicolas Straub

Reputation: 3411

js needs to run when the elements are available. Wrap the code in $(function () {}):

$(function () {
    $('.dropdown .title').on('click',function(){
        $(this).parent().toggleClass('select').find('.drop').toggle();
    });
    $('.dropdown .drop li').on('click',function(){
        var $this = $(this), input = $this.text();
        $('.dropdown .title').text(input);
    });
});

Upvotes: 1

Related Questions