Challenges with jQuery's 'this' selector in conjunction with if/else conditions

I am currently working on a project that involves allowing users to modify or move an image in the browser by clicking on buttons located on the side of the page. However, I am facing issues with the script in my if/else statement. Here is a snippet of what I have implemented in jQuery so far:

<meta charset="utf-8">
<title>Image Modification</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="js/main.js">
var menu = $('ul li').click(function() {
console.log($(this).index());


if (menu = 0) {
$('this').css('width', '80%')
}

else if (menu = 1) {
$('this').css('height', '80%')  
}

else if (menu = 2) {
$('this').css('height', '80%')
}

else if (menu = 3) {
$('this').css('top', '30')
}

else if (menu = 4) {
$('this').css('left', '50')
}

else if (menu = 5) {
$('this').css('left', -50')
}
else {

}
});
</script>
</head>
<body>
    <nav id="sidebar">
        <ul>
            <li>Edit 1</li>
            <li>Edit 2</li>
            <li>Edit 3</li>
            <li>Edit 4</li>
            <li>Edit 5</li>
            <li>Edit 6</li>
        </ul>
    </nav>
    <img class="active" src="images/picture.jpg" />
</body>

Answer №1

When using $('this'), you are selecting a <this> tag.

Correct format is $(this).

For if statements, remember that a single = is an assignment, which will be true if the value on the right is non-zero. To check for equality, use ==. Consider using a switch statement as shown below:

switch ($(this).index())  {
    case 0: // Do something
          break;
    case 1: // Do more
          break;
    default:
          // No match found
}

Answer №2

Essentially, your approach is incorrect because:

  • You should place your if/else statement inside the event handler
  • You should use comparison instead of assignment
  • You should not check the return value of the handler, but rather $('li').index();

Consider this HTML structure:

<nav id="sidebar">
     <ul>
         <li>Edit 1</li>
         <li>Edit 2</li>
         <li>Edit 3</li>
         <li>Edit 4</li>
         <li>Edit 5</li>
         <li>Edit 6</li>
     </ul>
</nav>
<section>
    <img class="active" src="http://lorempixel.com/400/200/" />
</section>

<section> is included for adjusting the height of the <img>

Here is the relevant CSS:

#sidebar li {cursor: pointer;}
#sidebar li:hover {color: purple;}
section {height: 200px;}
img {height: 100%; position: relative;}

To achieve the desired functionality, utilize the following jQuery code:

jQuery(function($) {

    $('#sidebar').find('li').on('click', function() {
        var position = $(this).index(), // the position of the <li> in the <ul>
            css = {
                property: null,
                value: null
            }, // storing CSS properties and values for the img
            $img = $('img'); // the image to apply CSS changes to

        // determine CSS properties and values based on the clicked <li> position
        switch(position) {
            case 0:
                css.property = 'width';
                css.value = '80%';
                break;
            case 1:
                css.property = 'height';
                css.value = '80%';
                break;
            case 2:
                css.property = 'height';
                css.value = '80%';
                break;
            case 3:
                css.property = 'top';
                css.value = '30px';
                break;
            case 4:
                css.property = 'left';
                css.value = '50px';
                break;
            case 5:
                css.property = 'left';
                css.value = '-50px';
                break;
        }

        // apply the CSS properties
        $img.css(css.property, css.value);

    });

});

View Working JSFiddle

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

What is the best way to reference a nested jQuery variable, whether global or local, within an HTML document

I've been working on this problem for days with no success. Any help would be greatly appreciated. I'm trying to call a variable from nested jQuery into HTML. The variable is named "PROBLEM". Even after trying to make it global, any updates made ...

Using an imported material icon as a background in JSS styling

I have implemented a draggable dialog component in React-mui with a resizable box feature. const styles = theme => ({ resizable: { position: "relative", "& .react-resizable-handle": { position: "absolute" ...

Display the accurate duration based on the dates selected in an HTML form automatically

If someone has office hours on Monday, Wednesday, and Friday from 7:00 am to 7:00 pm, and on Tuesday and Thursday from 10:00 am to 9:00 pm, the dropdown menu should display only the timings of 7:00 AM to 7:00 PM if the selected date is a Monday, Wednesda ...

How to create a slideToggle effect for nested ul and li elements

Initially, everything was working fine until I put it through the W3C validator. After fixing the errors, now it's not functioning as expected. I have created a jsfiddle The setup involves nested ul elements being used as dropdowns, with headers tha ...

"Is it possible in Typescript to set the parameters of a returning function as required or optional depending on the parameters of the current

I am currently exploring Typescript and attempting to replicate the functionality of styled-components on a smaller scale. Specifically, I want to make children required if the user passes in 'true' for the children parameter in createStyledCompo ...

Why isn't the response entity being returned following the ajax call?

So, I have a question regarding my attempt to send a simple post request to my controller using an URL as the post body. However, upon completion of the ajax call, I am not receiving any response from the controller. What could be causing this issue? Let ...

What advantages does Angular Service offer when gathering information compared to utilizing only $http?

Comparing Two Approaches: Approach A. Creating app module Using a service to store model data Implementing a controller to retrieve data from the service File 1: Users.js: angular.module('users', []); File 2: userService.js: angular ...

Converting JSON objects into datetime: A step-by-step guide

I am looking for a way to display JSON data in a Kendo chart. Below is the code I have: <head> <meta charset="utf-8"/> <title>Kendo UI Snippet</title> <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019 ...

The appearance of my website appears differently depending on the resolution

Just recently, I began exploring the world of HTML/CSS/JS and created a handy tool for my personal use. However, I encountered an issue when viewing it on different resolutions which caused some elements to look distorted. The tool I made allows me to inp ...

Tips for sending multiple values in a data object using jQuery AJAX

I am currently working on a form that contains two input fields, with the possibility of more being added later. The first input is a text field and the second is a checkbox. I want to be able to send these inputs using $.ajax. To accomplish this, I have ...

Tips for Utilizing Both getElementByID and getElementByTagName Functions in JavaScript

Hi! I'm a beginner in JavaScript and I've managed to retrieve some data using getElementById. Now, I want to extract a specific part using getElementsByTagName. document.getElementById('titleUserReviewsTeaser').innerHTML; " < ...

CSRF validation did not pass. The request has been cancelled. The failure occurred due to either a missing or incorrect CSRF token

Upon hitting the submit button in the login form, I encountered the following error message: Forbidden (403) CSRF verification failed. Request aborted. CSRF token missing or incorrect. settings.py MIDDLEWARE = [ 'django.middleware.security.Secur ...

Passing a JavaScript variable to a URL parameter can be achieved by

Can anyone advise me on passing JavaScript string variables and displaying them in the URL? For instance, let's say the URL is "xyc.com". Upon populating a variable (a), I wish for that variable to appear in the address bar as URL = "xyc.com/?a=". Cur ...

"Error alert: The specified property 'Iscontains' cannot be read because it is undefined" appears in the script for this video

I am currently utilizing AJAX to interact with my backend code. I retrieve URLs from the database and then render them onto the DOM, displaying videos accordingly. However, I am encountering an issue where Uncaught TypeError: Cannot read property ' ...

What is the best way to create a seamless Asynchronous loop?

Adhering to the traditional REST standards, I have divided my resources into separate endpoints and calls. The primary focus here revolves around two main objects: List and Item (with a list containing items as well as additional associated data). For ins ...

What is the best way to check for date equality in Node.js?

I am dealing with this code condition: stopped_at: { $lte: new Date(Date.now() - 86400 * 1000) } The above code successfully retrieves dates that are less than or equal to 24 hours ago. However, I am wondering if there is a simpler solution a ...

"Automatically close the fancybox once the form is confirmed in the AJAX success

Having an issue with closing my fancybox after submitting the registration form on my website. I am using the CMS Pro system.... Here is how I display the fancybox with the form: submitHandler: function(form) { var str = $("#subscriber_application"). ...

Issue with sidebar display inconsistency when resizing the window

Struggling with the sidebar display issue on mobile, as the menu appears outside the sidebar when resized. Is it feasible to relocate the bar to the top and resize it for a better mobile view experience? Adjusting the navbar's position affects the hea ...

What are some ways to incorporate inline TypeScript Annotations into standard JavaScript code?

If you're using VSCode, there's a new feature that allows you to implement type checking for traditional JavaScript files. There are instances where I wish to specify the type of a variable or parameters in a method or function to enhance auto-co ...

execute numerous queries simultaneously

I have a task of creating a bridge (script) that connects two databases, Mongo and Oracle. First, I execute three find queries on my MONGO database from three different collections: Collection 1 = [{ name: 'Toto', from: 'Momo', ...