What is a simple way to make toggling a .click event more efficient

Currently working on my final project for my webpage development course, I am focusing on creating a blog-themed website. My goal is to implement a feature where clicking on a profile picture expands it into a box displaying a bio and additional information. I have successfully completed this functionality, but now I am facing a challenge. I want the ability to click on the profile picture again to revert back to its original state, hiding the box and info. Despite trying various methods, such as .toggle, I have not been able to achieve the desired result. Any guidance or advice on how to accomplish this would be greatly appreciated. Thank you.

(JSfiddle wasn't functioning properly for me, apologies) > CodePen

JavaScript:

$(document).ready(function() {
  $('#picback').click(function() {
    $('#picback').animate({
      borderTopLeftRadius: 100,
      borderTopRightRadius: 100,
      borderBottomLeftRadius: 2,
      borderBottomRightRadius: 2,
      height: 460
    }, 'slow');
    $('#info').fadeIn('slow');
  });
});

Answer №1

Welcome to the year 2015 - where Javascript or jQuery are not required for this task!

Utilize CSS transitions and take advantage of the :checked pseudo-class. This method allows you to easily establish an initial state.

Check out the fully functional demo here: http://codepen.io/anon/pen/mJrvXo

#visibleToggle {
  display: none;
}
#picback {
  background-color: #B8B8B8;
  border-radius: 50%;
  width: 230px;
  height: 230px;
  border: 2px solid white;
  margin: 0 auto;
  box-shadow: 0 0 5px;
  text-align: center;
  transition-duration: 0.6s;
}
#picback:hover {
  box-shadow: 0px 0px 8px black;
  cursor: pointer;
}
#profilepic {
  height: 200px;
  position: relative;
  top: 16px;
  left: 2px;
}
#profilepic:hover {
  cursor: pointer;
}
#name {
  font-family: 'Playball', cursive;
  color: blue;
  text-shadow: 0 0 3px white;
}
#age {
  font-family: 'Pragati Narrow', sans-serif;
  font-size: 25px;
}
#bio {
  font-family: 'Roboto', sans-serif;
  color: white;
}
#info {
  opacity: 0;
}
#visibleToggle:checked + #picback {
  border-radius: 120px 120px 2px 2px;
  height: 460px;
}
#visibleToggle:checked + #picback #info {
  opacity: 1;
}
<input type="checkbox" id="visibleToggle" />
<div id='picback'>
  <label for="visibleToggle">
    <img src='https://www.shoptab.net/blog/wp-content/uploads/2014/07/profile-circle.png' id='profilepic' />
  </label>
  <div id='info'>
    <h2 id='name'>Joshua T. Hurlburt</h2>
    <h2 id='age'>15</h2>
    <p id='bio'>My name is Josh. I attend school as a freshman at Rhinelander High School. This is a project I made for my Web Page Development Final.</p>
  </div>
</div>

Answer №2

Here is my suggestion:

  • Try adding an active class to the picture element instead of using jQuery for animations upon clicking.
  • Use CSS only to animate the picture when it has the active class.
  • If the picture element already has the active class, remove it by clicking on the picture.

I wish I could provide you with specific code, but this advice should serve as a good starting point for your final project :) Best of luck!

Answer №3

Consider using pixel unit values in your CSS and JavaScript code. Check the display property of $("#info") when clicking on #picback to fade in and out #info, then reset #picback's CSS back to its initial borderRadius and height.

$(document).ready(function() {
  var picback = $("#picback")
  , info = $("#info");
  picback.click(function() {
    if (info.css("display") === "none") {
      $(this).animate({
        borderTopLeftRadius: 100,
        borderTopRightRadius: 100,
        borderBottomLeftRadius: 2,
        borderBottomRightRadius: 2,
        height: 460
      }, 'slow');
      info.fadeIn('slow');
    } else {
      $(this).animate({borderRadius:120,height:230}, 'slow');
      info.fadeOut('slow');
    }
  });
});
a {
  text-decoration: none;
  color: black;
  text-align: center;
}
#picback {
  background-color: #B8B8B8;
  border-radius: 120px;
  width: 230px;
  height: 230px;
  border: 2px solid white;
  margin: 0 auto;
  box-shadow: 0 0 5px;
}
#picback:hover {
  box-shadow: 0px 0px 8px black;
}
#profilepic {
  height: 200px;
  position: relative;
  top: 15px;
  left: 5px;
}
#name {
  font-family: 'Playball', cursive;
  color: blue;
  text-shadow: 0 0 3px white;
}
#age {
  font-family: 'Pragati Narrow', sans-serif;
  font-size: 25px;
}
#bio {
  font-family: 'Roboto', sans-serif;
  color: white;
}
#info {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<a href='#'>
  <div id='picback'>
    <img src='https://www.shoptab.net/blog/wp-content/uploads/2014/07/profile-circle.png' id='profilepic'>
    <div id='info'>
      <h2 id='name'>Joshua T. Hurlburt</h2>
      <h2 id='age'>15</h2>
      <p id='bio'>My name is Josh. I attend school as a freshman at Rhinelander High School. This is a project I made for my Web Page Development Final.</p>
    </div>
  </div>
</a>

Visit codepen http://codepen.io/anon/pen/zGKepE

Answer №4

For managing the click event on an image and toggling between different states of bio, it is recommended to utilize the .toggleClass() function in jQuery. This way, you can handle the toggling of classes (such as collapsed and expanded) directly through CSS.

Answer №5

Here is a straightforward solution using a simple variable to toggle between open and closed states. While there are more visually appealing examples out there, this one gets the job done with a basic closing animation. You may need to adjust the border radius in the callback function to avoid any strange effects.

$(document).ready(function() {
  var dropped = false;
  $('#picback').click(function() {
    if (!dropped) {
      $('#picback').animate({
        borderTopLeftRadius: 100,
        borderTopRightRadius: 100,
        borderBottomLeftRadius: 2,
        borderBottomRightRadius: 2,
        height: 460
      }, 'slow');
      $('#info').fadeIn('slow');
      dropped = true;
    } else { // Closing animation
      $('#picback').animate({
        borderRadius: "50%",
        height: "230px"
      }, 'slow');
      $('#info').fadeOut('slow');
      dropped = false;
    }
  });
});

Check out this example on CodePen for reference.

Answer №6

To create a dynamic interaction, you can implement a closure function that retains its previous state:

var toggleHandler = (function () {
    var isActive = false;
    return function () {
        isActive = !isActive; // Toggles between true and false
        if (isActive) {
            $('#picback').animate({
                borderTopLeftRadius: 100,
                borderTopRightRadius: 100,
                borderBottomLeftRadius: 2,
                borderBottomRightRadius: 2,
                height: 460
            }, 'slow');
            $('#info').fadeIn('slow');
        } else {
            // Implement close animation logic here
        }
    };
})();

$('#picback').click(toggleHandler);

Answer №7

Give this snippet a try. It includes functionality to add a CSS class when an animation is triggered, and then checks for its presence before initiating the next animation.

$(document).ready(function() {
  $('#picback').click(function() {
    var $this = $(this);
    if($this.hasClass('animated')) {
      $this.removeAttr('style').removeClass('animated');
    } else {
      $this.animate({
        borderTopLeftRadius: 100,
        borderTopRightRadius: 100,
        borderBottomLeftRadius: 2,
        borderBottomRightRadius: 2,
        height: 460
      }, 'slow').addClass('animated');
      $('#info').fadeIn('slow');

    }
  });
});

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 create a full-width dropdown menu with a nested dropdown in React JS?

https://i.sstatic.net/uoX2x.png Looking for a dropdown menu with nested dropdowns inside, I have tried using the standard bootstrap navbar method but haven't been successful. Here is my current code: <div class="dropdown"> <button class= ...

Adjusting Header Image to Match Screen Dimensions

I am currently struggling to make the header image on my new WordPress website resize dynamically based on the device I am using to view it. Despite trying various suggestions from different sources, I have not been able to achieve the desired result. The ...

Issue with AngularJS URLs not functioning properly when using HTML5 mode

Utilizing the AngularJS SPA template in Visual Studio. In my app.js file, I have the following code: $stateProvider .state('touranalysis', { url: '/touranalysis', templateUrl: '/views/touranalysis/index', ...

If a radio button is either selected or deselected, a jQuery alert will display the value of the radio button

When a user logs into the system, there is a radio button that is almost checked. I want to create an alert when the user clicks the button to show whether it is checked or unchecked. This is the HTML code for the radio button: <input id="radio1" name= ...

Node.js allows for downloading files from an FTP server to a client easily

System architecture The system is composed of 3 main components: 1: FTP server: Exclusively used for file storage, accessible only through the Node.js app. No direct access permitted. 2: Node.js: Acts as an API to interact with the FTP server. It is the ...

Retrieving vector layers by class and attempting to refresh them in OpenLayers version 2.14 is unsuccessful

First, the process involves accessing all Vector layers, checking if they are visible and retrieving their names. After that, we need to clear any applied filters on those layers and refresh them. Below is a snippet of the code: var mLayers = map.getLaye ...

Tips for handling a promise that has not been fulfilled

Is there a way to return a promise and trigger its failure block right away? Check out this unconventional method: if (fail) { var q = $q.deferred(); $timeout(function() { q.reject("") }, 1); return q.promise; } else { return ...

Displaying a div when a radio button is clicked in React

I am attempting to create a functionality where clicking on one radio button will display another div in React. As a beginner in React, I have tried implementing the code below but encountered issues with hiding and displaying the content based on user inp ...

Kendo Template Function: Angular JS version 1.6

I'm working with a currency column that looks like this: { field: 'INVOICE_AMOUNT_ORIGINAL', title: $translate.instant('invoiceAmount'), format: '{0:n}', template: '#= currency(dataItem.INVOICE_AMOUNT_ORIGIN ...

Erase blob_over from the Wordpress menu hover effect

I've created a unique style for the Donate button on this website, but I'm struggling to remove the hover effect. Any suggestions on where to start? Website URL: This is my Custom Class CSS: .donate { background:#4A1383; padding:0px 10px 0px 1 ...

Access Images from Server using Front-End Technology

I have a collection of images stored in a server folder that I want to display on a div element using client-side code. Initially, I tried to achieve this with AJAX, but it returned raw data instead of the image URL. Despite my efforts to find a solution, ...

Routes are no longer being qualified by Express once a subdomain is incorporated

We had developed a compact app that was working flawlessly, but then we were tasked with transforming it into something accessible for others in our organization to utilize... and that led to everything breaking down. Our initial setup included a simple ex ...

Generate a hierarchical JSON object by transforming a tree structure - Enhanced script

I am currently working on building a JSON object that updates dynamically as a node tree is constructed. The node tree will take user input and add it to the tree, while also updating the JSON object with the values. Here's what the JSON object should ...

Comparing hardware-accelerated CSS3 animations, transitions, and jQuery animate for mobile devices

While developing my app using PhoneGap and jQuery, I encountered a dilemma regarding animations. Initially, I relied on what I knew best - jQuery animate - to create smooth movements. However, discussions about hardware acceleration caught my attention. ...

a pair of radio buttons accompanied by a single submenu

Is there a way to extract the following code snippet from this block of HTML? <input type="radio" name="one" checked="checked" id="1"/> <label for="1">1</label> <input type="radio" name="one" id="2"/> <label for="2">2< ...

Member not found error with JQuery Autocomplete on browsers older than Internet Explorer 10

While constructing a web page with JQuery, I encountered issues with my autocomplete feature when testing it on IE8. The error message reads: SCRIPT3: Member not found. jquery-1.6.4.min.js, line 2 character 29472 After extensive research, I have been u ...

Adding and removing DateFields in Django formsets dynamically

I am encountering a unique issue specifically related to the django-bootstrap-datepicker-plus package. Within my Todo list application, I am aiming to enable tasks to appear on multiple specific dates. I have successfully set up my model, configured my fo ...

What is the correct way to incorporate a button into a fullcalendar?

element, I am currently utilizing the full calendar and implementing the following function: calendar: function(data, address){ var self = this; console.info(data); $('#calendar').fullCalendar({ height: 500, events: ...

Use jQuery to parse the JSON below and then showcase the information in an HTML table

Can anyone assist me with parsing the following JSON using jQuery and presenting it in an HTML table? I want to showcase the values of "key" and "doc_count" in an HTML table. Your help would be greatly appreciated. Please find the JSON data below: { ...

Understanding the Vue lifecycle methods for updating Vuex state

Utilizing Vue and Vuex components, the code within my component consists of: computed: { ...mapState({ address: state => state.wallet.address }) }, The functionality operates smoothly in the user interface. However, my objective is to invoke a ...