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

I need to generate table rows using v-for and include a unique value in the 'id' attribute of each row

I am creating table rows dynamically in a view using Flask data. <tr id="<% file.id %>" v-for="file in fileList"> <td><img class="thumbnail_preview" src=""></td> <td><% file.filename %></td> <td> ...

Comparing plain objects and class instances for modeling data objects

What is the recommended approach for creating model objects in Angular using TypeScript? Is it advisable to use type annotation with object notation (where objects are plain instances of Object)? For example, let m: MyModel = { name: 'foo' } ...

Is there a way for me to retrieve the return value from each of my promises?

Here's a helpful guide on how to efficiently handle multiple ajax requests with a dynamic number of objects. The process involves: var deferredArr = $.map($(".dynaload"), function(el, i) { return $.ajax({ url: $(el).data("loadUrl"), ...

Attempting to modify the background hue of a grid component when a click event is triggered

I am struggling with the syntax to change the color of an element in my grid when clicked. I have attempted different variations without success. Being new to JavaScript, I would appreciate some gentle guidance if the solution is obvious. JS const gri ...

Tips for effectively utilizing the overflow:auto property to maintain focus on the final

I am working on a Todo App and facing an issue where the scrollbars don't focus on the bottom of the page when adding a new element. How can this problem be resolved? https://i.stack.imgur.com/IzyUQ.png ...

Utilizing jQuery's multiple pseudo selectors with the descendant combinator to target specific elements

My code includes the following: <div class="a"><img></div> and <div class="b"><img></div> I want to dynamically enclose img tags with a div and utilize $(":not('.a, .b) > img") for ...

How can I trigger a function or automate code execution in Angular?

I have some code within a function that is crucial for initializing other variables. The issue I am facing is that this function does not execute unless it is called through another tag in the HTML. Is there a method to automatically initialize this func ...

Navbar active class not updating on jQuery page scroll

My one-page website has a fixed navbar that I want to change its active status when scrolling down to specific div positions. Even though I tried using jQuery, the code doesn't seem to work as intended. Here is the snippet: // SMOOTH SCROLLING PAGES ...

Efficiently select multiple classes in Material UI with just one target

I'm currently working with Material UI and I want to update the color of my icon class when the active class is triggered by react-router-dom's NavLink Here is my code: import React from "react"; import { makeStyles } from "@mater ...

The Limit of Time: ASP.NET AJAX Session Timeout

I am facing an issue with my code where sometimes I get strange messages and responses when calling an asp.net method due to session expiration. Instead of returning data, the code returns an aspx page. How can I implement a check in this method to detect ...

Changing all object values to true with React useState

In a certain file, I have defined an object with the following structure: export const items = { first: false, second: false, third: false } Within a component, I am using this object as shown below: import { items } from 'file'; const [el ...

Alignment of Inline SVG in HTML

I am struggling to align an inline SVG within a bounding DIV correctly, as shown in this example. <!DOCTYPE html> <html> <body> <div style="border: 1px solid black; height: 50px; width: 100px; vertical-align:top;"> < ...

What is the importance of having the same data type for the searchElement in the argument for Array.prototype.includes()?

Is there an issue with my settings or is this a feature of TypeScript? Consider the code snippet below: type AllowedChars = 'x' | 'y' | 'z'; const exampleArr: AllowedChars[] = ['x', 'y', 'z']; f ...

Maintain the visibility of the Jquery modal regardless of page loading

Hello, I am just getting started with jQuery and have encountered an issue. When I try to display a jQuery modal on the click of an Upload button, it disappears immediately because of the page load. I would like the modal to stay visible until a button wit ...

What is the best method for creating uniform cards with different amounts of text that won't cause overflow issues?

At the moment, I have a container that acts as a boundary for a group of cards: .cards-container { display: flex; align-items: stretch; justify-content: center; flex-wrap: wrap; margin-top: 20px; border: 5px solid violet; } .card { ...

Is it possible to prioritize loading JavaScript before images on a webpage?

My goal is to prioritize loading the js first and then the images for a specific reason. I want the blue rollover effect to be applied immediately upon loading. As the number of images on this page will eventually double, this could potentially become a la ...

"Hey, getting an error stating 'require is not defined' while attempting to configure the .env file. Need some help here

I am currently working on setting up a .env file to securely store the credentials for my Firebase database within a vanilla JavaScript project. Despite following various tutorials and referencing the documentation for dotenv, I continue to encounter an er ...

how to quietly change the focus of an element using jquery and css?

Whenever I modify the CSS of a scrolled-past element, the view abruptly jumps to that particular div (by scrolling up) upon applying CSS changes using .css(...). Something as simple as adjusting the background-color can trigger this effect. Is there a wor ...

What is the mechanism behind pushing an empty array into another empty array?

let arr = []; console.log(arr.push([])); // 1 Instead of logging [[]], the output is 1. Can someone explain what is happening in the code above? ...

Copying to the clipboard now includes the parent of the targeted element

Edit - More Information: Here is a simplified version of the sandbox: https://codesandbox.io/s/stupefied-leftpad-k6eek Check out the demo here: The issue does not seem to occur in Firefox, but it does in Chrome and other browsers I have a div that disp ...