JavaScript - Error: The '}' token was unexpected

Every time I attempt to move

<div id="test">this should go down</div>
downwards using:

<div onclick="(".test").slideDown(800);">close it</div>

I encounter an error whenever I click 'close it'

 SyntaxError: Unexpected token }

Kindly advise on what I might be doing incorrectly. Thank you :)

Answer №1

Here's a better way to do it:

<div onclick="$('.test').slideDown(800);">close it</div>

Alternatively, you can use this approach if you're already using jQuery:

<div id="close">close it</div>

Then, in a separate JavaScript file:

$('#close').click(function() {
    $('.test').slideDown(800);
});

By separating your markup and JavaScript, you can avoid the issues you're currently experiencing and keep your code more organized.

Answer №2

Modify one of the instances of double quotation marks (assuming you are utilizing jQuery, you will also have to include the $ shortcut (or complete jQuery function call):

onclick="$('.example').slideUp(600);"

// or

onclick='$(".example").slideUp(600);'

Answer №3

The mistake in your code is using an ID selector for the <div id="test">, but attempting to animate the <div> with a class selector $(.test), which will not work. Additionally, the incorrect quotes in your code are causing a SyntaxError. To resolve these issues, you can try the following solutions :-)

HTML:

<div id="closeIt">close it</div>

JavaScript:

$('#closeIt').click(function() {
    $('#test').slideDown(800);
});

or Complete example (with separate bound function):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function() {
            $('#closeIt').click(function() {
                $('#test').slideDown(800);
            });
        });
    </script>
    <style type="text/css">
        #test {
            display:none;
        }
    </style>
</head>
<body>
<div>
<div id="closeIt">close it</div>
<div id="test">this should go down</div>
</div>
</body>
</html>

or inline onclick (not recommended as this doesn't separate markup from behaviour but it still works)

<div onclick="$('#test').slideDown(800);">close it</div>

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

When implementing a Vue component, you may encounter a 'parentNode' TypeError

I'm experiencing an issue with a page that is only partially rendering. Specifically, the page renders Listings but not Bookings. After some investigation, I discovered that removing the divs associated with isReviewed() resolves the rendering issue. ...

Solving required packages in Express server

I am encountering difficulties with resolving dependencies on my express server. Below is the structure of my project: Calculator --dist ----app -------calculator.js -------server.js --node_modules --src ----app --------calculator.js --------server.js -- ...

Error: React cannot read property 'any' since it is undefined

I am brand new to React and currently in the process of building a small app by following a tutorial on Udemy. The app includes a form, and while trying to import the redux-form library into my project, I encountered the following console error: https://i ...

Partially translucent electron window

Is there a way in Electron to create a view similar to the finder in macOS, where the sidebar is opaque and the main content is not? https://i.stack.imgur.com/UKXg2.jpg I am aware of how to make an entire window opaque, but I'm unsure if it's p ...

Ensure that all asynchronous code within the class constructor finishes executing before any class methods are invoked

Looking to create a class that takes a filename as a parameter in the constructor, loads the file using XmlHttpRequest, and stores the result in a class variable. The problem arises with the asynchronous nature of request.onreadystatechange, causing the ge ...

Personalizing the label of a select input using materialui

Working on customizing a select element using the "styled" method: const StyledSelect = styled(Select)` height: 2rem; color: #fff; border-color: #fff; & .${selectClasses.icon} { color: #fff; } & .${outlinedInputClasses.notchedOutl ...

Using the Spread Operator to modify a property within an array results in an object being returned instead of

I am trying to modify the property of an object similar to this, which is a simplified version with only a few properties: state = { pivotComuns: [ { id: 1, enabled : true }, { id: 2, enabled : true ...

How can you attach a d3 graphic to a table that was created automatically?

Calling all experts in d3, I require urgent assistance!! On this web page, a JSON is fetched from the server containing 50 different arrays of numbers and related data such as 90th percentiles, averages, etc. A table is dynamically created with the basic ...

Check for non-null Sequelize Where conditions

Suppose I need to execute a select command using Sequelize with the condition: WHERE ID=2134 However, if the user does not provide an ID, then the WHERE clause should be omitted (as it is null). What is the best way to handle this situation in Sequelize ...

Gain access to Google Analytics without the need for page consent by utilizing JavaScript

I am currently building a dashboard with Atlasboard. My goal is to retrieve Google analytics data such as page views, and I plan to run specific queries which can be found here. Is there a method to access my Google analytics data without the consent pag ...

Angular 2 - Changes in component properties not reflected in view

I'm currently delving into Angular 2 and as far as I know, interpolated items in the view are supposed to automatically update when their corresponding variable changes in the model. However, in the following code snippet, I'm not observing this ...

React Native's NativeBase checkbox component: Overlapping text causing the content to extend beyond the confines of the screen

I am having trouble getting the text inside a checkbox (using nativebase) to shrink. Does anyone know why this is happening? Do I need to add some flex properties? import React from "react" import {Box, Center, Checkbox, Heading, NativeBaseProv ...

Querying with mongodb using the $or operator yields a single result

I need help querying my MongoDB using JavaScript as I am only getting one result when I should be utilizing the $or operator. The frontend sends a string, which I then split by spaces to search for matches in the database based on skills, location, and na ...

Tips for passing state values into getServerSideProps to fetch data from an API

At the moment, I am dealing with a situation where I have a context containing the state of a name. My current task is to extract this state so that I can utilize it in an API call which relies on it. age.js import { useStateContext } from "@/context ...

Determination of Vertical Position in a Displayed Table

I am trying to incorporate infinite scrolling with an AJAX-based loader in the body of an HTML table. Here is a snippet of my HTML code: <table> <thead> <tr><th>Column</th></tr> </thead> <tbody> ...

Rotating the icon in Bootstrap Accordion upon opening

I am trying to customize a Bootstrap 4 accordion by conditional rotating the icon to point up when it is open and back down when closed. I managed to achieve this using CSS, but now I need to implement it conditionally based on active states rather than ev ...

Timeout error for WebSocket connection on JavaScript client

My first attempt at using websockets is not going as planned. Since my IP address changes frequently, I decided to make the following websocket call on the server-side: $echo = new echoServer("myurl.com","9000"); On the client-side, I'm making the f ...

Exploring the power of Knockout Js and Typeahead libraries

https://i.stack.imgur.com/38iZc.png Hello experts in Knockout and typeahead, I am receiving suggestions from the typeahead js as shown above. I have my data supplied in an array format var itemsRandom= ['Apple', 'Ball','Ape&apos ...

Updating the value of the chosen drop down option upon selection

I currently have a Material UI dropdown menu implemented in my project. My goal is to use the selected option from the drop down menu for future search functionality. How can I utilize onChange() to store the selected option effectively? At the moment, I ...

javascript authorization for iframes

I am currently working on a localhost webpage (parent) that includes an iframe displaying content from another url (child; part of a different webapp also on localhost). My goal is to use JavaScript on the parent-page to inspect the contents of the iframe ...