Harshil Shah Harshil Shah - 5 months ago 20x
Javascript Question

Error while converting javascript code to jquery code

i have following code where openNav function is called.

<div id="main">
<h2>Sidenav Push Example</h2>
<p>Click on the element below to open the side navigation menu, and push this content to the right.</p>
<span id="sp1" style="font-size:30px;cursor:pointer" onclick="openNav()">☰ open</span>

i have Javascript code which works fine

function openNav() {
document.getElementById("mySidenav").style.width = "250px";
document.getElementById("main").style.marginLeft = "250px";

i tried to convert it in jquery but it shows error openNav is not defined.

<script type="text/javascript">
$('#sp1').click(function openNav() {
$('#mySidenav').style.width = "250px";
$('#main').style.marginLeft = "250px";

It compiles and run properly but when i click on
open (onclick event)
it throws an exception that openNav is undefined.

Please explain what is the problem ?


Pure jQuery - You need to use the css method

    $('#mySidenav').css( "width", "250px" );
    $('#main').css( "margin-Left", "250px");

Your approach - Or simply access the DOM element from jquery object using [0] index

   $('#mySidenav')[0].style.width = "250px";
    $('#main')[0].style.marginLeft = "250px";