• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • VBA
  • About
You are here: Home / jQuery / onclick this jQuery

onclick this jQuery

November 24, 2021 Leave a Comment

The example below shows how onclick and $(this) work together. When using jQuery, we can use the click() method to make things even easier.

$("#div").click(function(){
    $(this).css("background-color", "green"); // Would change the background color of element #div to green
    $(this).hide(); // Results in the element #div being hidden
}); 

Another way this can be done is to use the .on() method:

$('#div').on("click", function(event) {
    $(this).hide(); // Results in the element #div being hidden (or display none).
});

Below is another example of using onclick and $(this).

<div id="div1">
    <img src="#someurl">
    <p>Text 1</p>
    <p>Text 2</p>
</div>

$("#div1").click(function(){
    $("img", this).hide(); // Results in the img element inside of #div1 being hidden.
});

Other Articles You'll Also Like:

  • 1.  Using jQuery to Change Image src
  • 2.  Using jQuery to Get the Previous Sibling of an Element
  • 3.  Using jQuery to Toggle Class of HTML Element
  • 4.  How to Use jQuery to Remove Element
  • 5.  jQuery Opacity – How to Change the Opacity of an Element
  • 6.  jQuery next – Get the Next Element of a Div
  • 7.  Get Padding of an Element Using jQuery
  • 8.  jQuery before – Insert HTML Before Another Element
  • 9.  jQuery fadeIn – Fading In Element in HTML
  • 10.  jQuery keydown Method

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

The Programming Expert is a compilation of hundreds of code snippets to help you find solutions to your problems in Python, JavaScript, PHP, HTML, SAS, and more.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2022 · The Programming Expert · About · Privacy Policy