Display a specific tab section upon clicking using jQuery or JavaScript

Hello everyone! I am completely new to JavaScript. I have added a tab slider to my HTML with 3 categories in the tab menu: All, Creative, and Branding. How can I show a div after clicking on one of the list items? I have assigned classes to the list items and created two divs for the images, but what is the next step? Below is the code snippet.

$(document).ready(function(){

$("ul li").click(function(e) {

// make sure we cannot click the slider
if ($(this).hasClass('slider')) {
return;
}

/* Add the slider movement */

// identify which tab was clicked
var whatTab = $(this).index();

// Calculate how far the slider needs to move
var howFar = 160 * whatTab;

$(".slider").css({
left: howFar + "px"
});

/* Add the ripple effect */

// Remove old ripples
$(".ripple").remove();

// Setup
var posX = $(this).offset().left,
posY = $(this).offset().top,
buttonWidth = $(this).width(),
buttonHeight = $(this).height();

// Add the element
$(this).prepend("<span class='ripple'></span>");

// Make it round!
if (buttonWidth >= buttonHeight) {
buttonHeight = buttonWidth;
} else {
buttonWidth = buttonHeight;
}

// Get the center of the element
var x = e.pageX - posX - buttonWidth / 2;
var y = e.pageY - posY - buttonHeight / 2;

// Apply CSS styles and start the animation
$(".ripple").css({
width: buttonWidth,
height: buttonHeight,
top: y + 'px',
left: x + 'px'
}).addClass("rippleEffect");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container3">
<h1>OUR PORTFOLIO</h1>
<p>Lorem ipsum lore exciting
ipsum lore portfolio</p>
<div class="portfolio">
<ul>
<li class="all">All</li>
<li class="creative">Creative</li>
<li class="branding">Branding</li>
<li class="slider"></li>

</ul>

<div class="photo" id="photo" style="display:none">
<img src="img/icon2.png"/>
</div>
<div class="photo2" id="photo2"style="display:none">
<img src="img/icon3.png"/>
</div>

</div>

Answer №1

I'm not quite sure what you're asking, but I hope this is the information you were looking for.

$('.all').click(function(e){
$('.hide').removeClass('hide')
})

$('.creative').click(function(e){
$('.photo').removeClass('hide')
$('.photo2').addClass('hide')
})

$('.branding').click(function(e){
$('.photo2').removeClass('hide')
$('.photo').addClass('hide')
})
.hide
{
display:none

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container3">
    <h1>OUR PORTFOLIO</h1>
    <p>Lorem ipsum lorem exciting
      ipsum lore portfolio</p>
      <div class="portfolio">
        <ul>
  <li class="all">All</li>
  <li class="creative">Creative</li>
  <li class ="branding">Branding</li>


</ul>

<div class="photo hide" id="photo" >
  <img src="img/icon2.png"/>
</div>
<div class="photo2 hide" id="photo2" >
  <img src="img/icon3.png"/>
</div>

</div>

Answer №2

Extract the class of the clicked element and then toggle the visibility of a div based on it.

<script type="text/javascript">
$(document).ready(function(){

$("ul li").click(function(e) {


var currentClass = $(this).attr('class');

if(currentClass == "all") {
  $("#photo").css("display","block");
} else if (currentClass == "creative") {
  $("#photo2").css("display","block");
}



// Prevent clicking on the slider
if ($(this).hasClass('slider')) {
  return;
}

/* Implement slider movement */

// Determine which tab was clicked
var whatTab = $(this).index();

// Calculate the distance the slider needs to move
var howFar = 160 * whatTab;

$(".slider").css({
  left: howFar + "px"
});

/* Create a ripple effect */

// Remove existing ripples
$(".ripple").remove();

// Setup
var posX = $(this).offset().left,
    posY = $(this).offset().top,
    buttonWidth = $(this).width(),
    buttonHeight = $(this).height();

// Add the element
$(this).prepend("<span class='ripple'></span>");

// Make it round!
if (buttonWidth >= buttonHeight) {
  buttonHeight = buttonWidth;
} else {
  buttonWidth = buttonHeight;
}

// Get the center of the element
var x = e.pageX - posX - buttonWidth / 2;
var y = e.pageY - posY - buttonHeight / 2;

// Apply CSS for ripples and start the animation
$(".ripple").css({
  width: buttonWidth,
  height: buttonHeight,
  top: y + 'px',
  left: x + 'px'
}).addClass("rippleEffect");
});
});  
</script>

Answer №3

Here is a simple way to show or hide images based on their class names:

$('.container3 li').click(function(e){
 let className = $(this).attr('class');
 if(className == "all"){ //if all tab pressed
    $("#portfolio-gallery .photo").show(200);
  }else{
    $("#portfolio-gallery .photo").hide();
    $("#portfolio-gallery .photo."+className).show(200);
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="container3">
      <h1>OUR PORTFOLIO</h1>
      <p>Lorem ipsum lorem exciting ipsum lore portfolio</p>
      <div class="portfolio">
      
       
       <ul>
        <li class="all">All</li>
        <li class="creative">Creative</li>
        <li class ="branding">Branding</li>
       </ul>

    <div id="portfolio-gallery">
     <div class="photo creative" >
       <img src="img/icon2.png"/>
     </div>
     <div class="photo branding" >
       <img src="img/icon3.png"/>
     </div>
     <div class="photo branding" >
       <img src="img/icon2.png"/>
     </div>
     <div class="photo branding" >
       <img src="img/icon3.png"/>
     </div>
    </div>

 </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

"Encountering issues with autocomplete feature loading empty data when attempting to populate several fields simultaneously

Encountering issues with autocomplete when trying to select a value and fill in multiple fields. Seeing small blank lines on autocomplete and search stops while typing. Suspecting the problem lies within .data("ui-autocomplete")._renderItem or ...

Sending an array of functions to the onClick event of a button

Having difficulty with TypeScript/JavaScript Currently working with an array of functions like this private listeners: ((name: string) => void)[] = []; Successfully adding functions to the array within another function. Now looking to trigger those ...

What is the best way to arrange an array using AngularJs or Javascript?

When a user makes a selection, I want to sort and display an array in alphabetical order. Specifically, when we render data from the backend, I would like to display the fullName in alphabetical order. The $scope.selectedControlOwner is the ng-click event ...

Obtaining an element within an object using a jQuery selector

I'm currently attempting to utilize a jQuery selector on data received from an ajax call. Below is the code snippet I am working with - $.ajax({ url: 'moo.html', success: function ( code ) { var divs = $(code).filter(functi ...

How can we verify that the client has successfully completed the file download process?

I am currently working with a single large file. My goal is to accomplish the following tasks: 1) Upload the file to the server 2) Automatically delete the file from the server once it has been successfully downloaded by the user. Is there a method to ...

Access to PHP script (IF) unattainable following a POST occurrence

I'm completely new at this. I am attempting to create a contact form using HTML5 and PHP mail function, but I am facing an issue with my form action pointing to contacto.php. After submitting the form, it seems to be skipping over the IF condition wi ...

Creating JSON data that is completely valid using client-side JavaScript

I've been working on creating a JSON explorer/editor. Successfully managed to parse the initial JSON into the div and customize the formatting. Here's the function I utilize to loop through the initial JSON: _iterate(_tab, raw_json){ var tab ...

Is it possible to nest Route components in react-router version 4.x?

How can one properly implement nested routes in react-router version 4.x? Previous methods like the one below worked well, but upgrading to version 4.x now results in a warning... <Route path='/stuff' component={Stuff}> <Route path=&a ...

Storing multiple items in an array using LocalForage

I have a challenge where I need to add multiple items to an array without overriding them. My initial approach was like this: localForage.getItem("data", (err, results) => { console.log('results', results) // var dataArray ...

Failure to specify the variable type can lead to the creation of automatic global variables

Recently, I stumbled upon this http://www.w3schools.com/js/js_scope.asp page which introduced me to the concept of "Automatic Global variables". Here is an example of how it works: // You can use carName variable here function myFunction() { carName ...

Combining Mocha, BlanketJS, and RequireJS has resulted in the error message "No method 'reporter'."

While using Mocha with RequireJS, my tests are running smoothly. However, I encountered an issue when trying to incorporate blanket code coverage. The error Uncaught TypeError: Object #<HTMLDivElement> has no method 'reporter' keeps popping ...

What is the process for retrieving an object from a node.js server using JSON.stringify() in a JavaScript file?

Looking to organize my code, I want to separate the JavaScript from my page and link it through a file instead of having it embedded within script tags. The issue arises when I receive a "SyntaxError: expected expression, got '<' " in Firefox ...

Search for data in Mongoose by utilizing a query object that has been obtained from a query string

After extracting and parsing a querystring from a URL, I am able to map it into an object structure like this: { '$and': [ { length: { '$gt': '2' } }, { length: { '$lt': '55555' } } ] } This object is st ...

Building a basic music player with the <audio> element and JavaScript / jQuery

I am new to Javascript and jQuery, and this is my first time posting a question here. I have been trying to create custom functions for the HTML5 audio tag by following tutorials online. Despite my efforts, I cannot seem to get it working. Although I can m ...

Can the text value be read and its strings changed?

I need to modify the message inside an H2 element with the code provided below. I want to change the text from No results were found for this query: <em class="querytext"> to "No results were found by hello world!, but the catch is that I cannot di ...

How can I assign several Objects to a single array?

My goal is to save several objects into an array. Specifically, I have five objects named obj1, obj2, obj3, obj4, and obj5. ...

Is there a way to confirm that the content of two files is identical?

Currently, I am utilizing mocha/supertest/should.js for testing a REST Service. When I make a request to GET /files/<hash>, it returns the file as a stream. I am seeking guidance on how to use should.js to assert that the contents of the file are i ...

Segment the progress bar into sections

Struggling with an Angular app, and still new to HTML and CSS, I am attempting to create a unique progress bar. I aim to split each section of the progress bar into two subsections with distinct background colors shown in this image: https://i.sstatic.net/ ...

Send information from a jQuery post to a PHP script and then have it appear instantly on the same PHP file

Looking for a solution to post data to a php script called showitemid.php using ajax and open the same script in a thickbox upon clicking a hyperlink? The goal is to display the posted data on showitemid.php. Check out my code below: postitemid.php In th ...

What is the best way to showcase the contents of an array of objects from JavaScript on an HTML page in a dynamic

Looking for guidance in Javascript as a beginner. For an assignment, I need to create two separate JS files and use them to display data dynamically on an HTML page. One JS file, named data.js, contains an array of objects representing a product catalog. T ...