Achieving functionality with dropdown menus in jQuery

I am facing an issue with a dropdown menu that works perfectly in jsFiddle during testing, but does not function as expected when I run it on my testing server.

jsFiddle: http://jsfiddle.net/cyberjo50/39bu8/2/

HTML

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-2.1.1.js"></script>
<script type="text/javascript" src="toggle.js"></script>

</head>

<body>
<button>Select Destinations<img src="images/down-arrow.png" width="20" height="20" alt=""   style="vertical-align:middle; padding-top: 0px;"/></button> 
<nav id="menu">     
<a href="#">Philadelphia</a>
<a href="#">United States of America</a>
<a href="#">Philippines</a>
<a href="#">Long Destinations Names</a>
<a href="#">Some Destination</a>
<a href="#">Australia</a>
</nav>
</body>
</html>

Javascript

img_arrow = '<img src="images/down-arrow.png" width="20" height="20"/>';

$(function ()
{
var $window = $(window),
    $nav = $('nav'),
    $button = $('button');

$button.on('click', function ()
{
    $nav.slideToggle();
});

$window.on('resize', function ()
{
    if ($window.width() > 320)
    {
        $nav.show();
    }
});
});
$('#menu a').click(function(e){

$('button').html($(this).html() + img_arrow);

e.preventDefault();
});

Here is my test page:

I cannot figure out why the dropdown menu is not functioning correctly on my test page. It should work similar to the one in Jsfiddle. The code used in the fiddle is exactly the same as what is implemented in my testing link.

Answer №1

The issue in your code is that the click handler is being executed during page load instead of after it. You can use $(function(){}) as a shorthand for $(document).ready(). To resolve this problem, make sure to move the assignment of the click handler inside the onDOMReady call:

$(function (){
    var $window = $(window),
        $nav = $('nav'),
        $button = $('button');

    $button.on('click', function (){
        $nav.slideToggle();
    });

    $window.on('resize', function (){
        if ($window.width() > 320){
            $nav.show();
        }
    });

    $('#menu a').click(function(e){
        $('button').html($(this).html() + img_arrow);

        e.preventDefault();
    });
});

http://jsfiddle.net/39bu8/4/

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

React Native: Avoiding Infinite Loops in useEffect

I am facing an issue where my app goes into an infinite loop because pointsData is inside the useEffect function. How can I resolve this situation? function useGetPoints() { const [pointsData, setPointsData] = useState<PointTbleType[]>([]); ...

Strip away the HTML tags and remove any text formatting

How can I effectively remove HTML tags and replace newlines with spaces within text? The current pattern I am using is not ideal as it adds extra space between words. Any suggestions on how to improve this pattern? replace(/(&nbsp;|<([^>]+)> ...

Adjustable dimensions and proportions for the following image

I'm currently working on a blog page using next.js and I've encountered an issue with displaying images. Each post has a main image of varying dimensions and aspect ratios, making it difficult to maintain consistency when scaling for smaller scre ...

Execute JavaScript/AJAX solely upon the selection of a button

Currently, my script is being executed immediately after the page loads and then again after a button click. Is there any way to modify it so that the script waits until I click the button before running? As far as I understand, this code runs asynchronous ...

Tips for maintaining the selected radio button state after refreshing the JSP page: Ensuring that the radio button remains selected

I need help with refreshing a page after clicking on one of two radio buttons. I've tried multiple solutions but haven't been successful so far. Can someone assist me? <script> $(document).ready(function() { $(document).on('c ...

Combining d3 and vue.js for enhanced interactive visualizations

I am currently in the process of integrating D3 with vue.js and I am following a straightforward guide available here: The guide suggests appending a new div for each new bar, which I have successfully accomplished using a custom directive as shown in the ...

Using Jquery to switch controls to labels for a read-only form display

Looking for a solution where a form can be displayed in view-only mode without making controls read-only. The requirement is to show the values of text boxes, drop downs, and list boxes (comma delimited) as labels when the user has read-only access to the ...

Encountered an error with Winston and Elasticsearch integration: "TypeError: Elasticsearch is not a constructor

I recently implemented winston-elasticsearch on my express server by following the code provided in the documentation var winston = require('winston'); var Elasticsearch = require('winston-elasticsearch'); var esTransportOpts = { le ...

Update the image source through an AJAX call

I've experimented with various methods to update an image src using an AJAX request. The new URL is obtained through the AJAX call, and when inspecting the data in Developer Tools, the 'DATA' variable contains the correct URL. However, the i ...

Managing component composition in React/TypeScript: What's the best way to approach it?

I am brand new to the world of typescript, so please be patient with me. My objective is to transform this react component: interface ButtonProps {...} const Button: React.FC<ButtonProps> = ({ children, href, value as = 'button', ...

Navigating through items and organizing based on several criteria

In JavaScript, I am currently learning about accessing objects and sorting them based on multiple conditions. As a beginner in JavaScript, this may seem like a very basic question to some. My task involves sorting based on the 'status' field. va ...

Moving a div with arrow keys using percentages: A step-by-step guide

I found this amazing script on Stack Overflow that allows me to move elements around the page using arrow keys. It works flawlessly, and I love how it enables diagonal movement by combining different arrow key inputs. Now, my query is whether it's fe ...

Transferring Data between Rails and Angularjs using JSON

Utilizing Angularjs to fetch JSON data from a Rails test app deployed on Heroku is proving to be a bit challenging. Below you can find the snippets of my Angular and Rails code. An error message displayed in my Firebug console reads: "NetworkError: 404 N ...

Error: Definition Already Exists

I'm currently debugging a layout and encountering some peculiar errors. The page is being served as DTD XHTML 1.0 Strict. The error message looks like this: ID "OFFICENAME" already defined: div class="office" id="officename" ID "OFFICENAME" origin ...

The carousel is failing to display two items on each slide

I've integrated a carousel library from npm into my project. However, I'm facing an issue where I need to display two cards in each slide within the carousel. Here's a snippet of my code: Catalog.js import React from 'react'; impo ...

I am encountering an issue where my Vue navbar is successfully changing the route but not updating the corresponding router-view

I have been working on a single-page application using Vue and I encountered an issue with the navbar when navigating through routes. The problem is that after the first click on a navbar item, the route changes successfully but the router-view does not up ...

Exploring the efficiency of AngularJS when binding to deeply nested object properties

Are there any performance differences to consider when data binding in Angularjs between the following: <div>{{bar}}</div> and <div>{{foo.bar}}</div>? What about <div>{{foo.bar.baz.qux}}</div>? Our team is working o ...

What is the best way to remove table cells from a TableBody?

Currently, I am in the process of designing a table to display data retrieved from my backend server. To accomplish this, I have opted to utilize the Table component provided by Material UI. The data I retrieve may either be empty or contain an object. My ...

Establishing the highest allowable value limit in cleave

I've integrated cleave.js into my Vue.js project to create a date input field. Here's the option configuration I used: <cleave :options="{ date: true, datePattern: ['m', 'd','Y'] ...

Is there a way to restrict jQuery Backstretch to only display on the homepage?

I am facing an issue with the jQuery function "Backstretch" on my blog. I only want it to be displayed on the homepage but the black background image seems to blend in with the slideshow on other pages. Can someone suggest a way to restrict the slideshow ...