Tips for crafting paragraphs that double as sieves

I'm trying to simplify and shorten this code. I have three HTML paragraphs acting as filters: "all", "positive," and "negative", referring to reviews. Each has a corresponding div for reviews: "allcont", "poscont", and "negcont". Clicking on any of the filter paragraphs should display only its corresponding review div. I want to create filter buttons for different reviews with cleaner code.

Here's the current code:


var allcont = document.getElementById("allcont");
var poscont = document.getElementById("poscont");
var negcont = document.getElementById("negcont");
var all = document.getElementById("all");
var positive = document.getElementById("positive");
var negative = document.getElementById("negative");

all.onclick = function(){
    allcont.style.display = "block";
    poscont.style.display = "none";
    negcont.style.display = "none";
    all.style.color = "red";
    positive.style.color = "white";
    negative.style.color = "white";
}

positive.onclick = function(){
    poscont.style.display = "block";
    allcont.style.display = "none";
    negcont.style.display = "none";
    positive.style.color = "red";
    all.style.color = "white";
    negative.style.color = "white";  
}

negative.onclick = function(){
    negcont.style.display = "block";
    poscont.style.display = "none";
    allcont.style.display = "none";
    negative.style.color = "red";
    all.style.color = "white";
    positive.style.color = "white";
}

When a filter paragraph is clicked, it changes color to red (as outlined in the code).

The existing code works but feels overly complex. I believe we can achieve this functionality more efficiently using a loop or similar method. Looking forward to your suggestions!

Answer №1

Although I typically avoid recommending jQuery, using it can simplify the process.

$(function(){
  $(".pfilter").on("click", function(){
    var $this = $(this);
    $(".cont").hide();
    $("#"+$this.data("show")).show();
    $(".pfilter").css("color", "blue");
    $this.css("color", "red");
  });
});
p {
  cursor: pointer;
  display: inline-block;
  margin: 0 10px;
  color: blue;
}

div.cont {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="all" data-show="allcont" class="pfilter">ALL</p>
<p id="positive" data-show="poscont" class="pfilter">POSITIVE</p>
<p id="negative" data-show="negcont" class="pfilter">NEGATIVE</p>
<hr>
<div id="allcont" class="cont">ALLCONT DIV</div>
<div id="poscont" class="cont">POSTCONT DIV</div>
<div id="negcont" class="cont">NEGCONT 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

Sending objects as parameters to a class in JavaScript - an easy guide

Having trouble passing a parameter to the class for handling AJAX errors. The initial function is as follows: function GetLastChangePass(UserId) { var field = { id: UserId, } var fieldStringified = JSON.stringify(field) $.ajax({ ...

Struggling to dynamically create form controls within Angular forms and receiving the following error in the console: "TypeError: feature_r5.get is not a function"

When I click a button in my Angular v14 HTML template, I am trying to dynamically generate form controls and although I am able to generate them, an error is popping up in the console. ERROR TypeError: feature_r5.get is not a function at PostAdvComponent_ ...

Is Passport.js' serializeUser and deserializeUser functions never triggering?

Encountering an issue with Passport-local. It seems that neither serializeuser nor deserializeUser are being invoked. Upon researching similar problems on SO, it appears that many others facing this problem were not properly including bodyParser. Below is ...

Handling an HTML Form without the Submit Button using VeeValidate

I've implemented a form handler using its composable feature in my <script setup>: const { submitForm, resetForm, handleSubmit, meta } = useForm() function save() { // Want to submit the form here submitForm() // Not working showSaveSnac ...

The Google Maps API has been successfully initialized, however, it is experiencing difficulties being displayed on the webpage

I have been successfully using a custom Google API on various web pages. However, I encountered an issue where the map API loads successfully but is not displaying on a specific web page. Below are the relevant code snippets: <html> <head> &l ...

"Tree panel items in ExtJS 4 are displaying correctly in Firefox, but are mysteriously missing from

While working on my Tree Panel project, I encountered an issue with the display of items in different browsers. The items show up correctly in Firefox but appear empty in Chromium. How is this possible? Here's the JSON data sent to the server: {"tex ...

Vue Router generates a URL containing %2F when dealing with slug routes

I am facing an issue in my Vue 3 application where I need to create a route for dynamic slugs. Currently, when using RouterLink, the generated URL contains %2F instead of actual slashes which is not the desired result. For example, the current URL looks l ...

Chat box custom scrollbar always positioned at the bottom

I have a personalized chat box where I included overflow-y for scrolling functionality. However, every time I input a message in the text box, it displays at the top of the scrollbar window. Is there a way to automatically show the most recent message I ...

Tips for resolving the React Hook Type Error issue

Error Image const isLoggedIn = true; const handleChangeEvent = () => {}; const [displayPassword, setDisplayPassword] = useState(false); const handleTogglePassword = () => setDisplayPassword((prevDisplayPassword) => !prevDi ...

What is causing the issue where Multiple file selection does not work when using the multiple attribute

I am having issues with uploading multiple files on my website. I have created an input field with the attribute multiple, but for some reason, I am unable to select multiple files at once. app.html <input type="file" (change)="onChange($event)" req ...

Unable to view Google Map markers within my XPath elements while using Selenium?

Looking to extract data from a Google Maps applet. The specific page can be found here: You can click on items on the map to view displayed information. While typical Google Maps show marker elements, I cannot see them on the provided link when inspecti ...

What is the best way to have text wrap around an icon in my React application?

I am facing an issue while trying to display the note description over the trash icon in a React app. I have tried various methods but can't seem to achieve the desired effect. Can anyone guide me on how to get this layout? Here is what I intend to a ...

What is the best way to define a custom route in react-router-dom?

My goal is to have the URL display "/login" in the address bar when I am on the login page. // App.js <Routes> {isLoggedIn ? ( <Route path="/" element={<Root onLogout={handleLogout} />}> <Route index e ...

Tips for Customizing the StrongLoop LoopBack Explorer CSS

Our team is currently utilizing Strongloop's LoopBack framework for our REST APIs and we are looking to customize the CSS of the LoopBack Explorer. Unfortunately, it seems unclear which CSS files are being employed (LoopBack vs Swagger) and their exac ...

Troubleshooting issue: PHP INSERT Prepared statement not working when using AJAX

Currently, I am trying to construct an INSERT statement using AJAX along with a prepared statement in PDO. This is my first attempt at combining AJAX and PDO, so there might be mistakes due to lack of experience. In its current state, I keep encountering ...

Challenges faced when retrieving data from a web API using JavaScript with REACT

Having trouble retrieving data from a Web API in React. The API URL is and I've stored it in a state called pokeData. When I do a console.log(pokeData), everything works fine. Likewise, there are no issues with console.log(pokeData.types). However, ...

Unable to eliminate user registration feature with Meteor and React

Exploring the world of Meteor and diving deep into its functionalities, I am currently focused on creating a user login and signup page with personalized control panels for each registered user. Although I have successfully implemented the signup and logi ...

How can I create a timed slideshow of images?

Is there a way to make a series of images slide automatically after closing or stopping a video? To see the specific website in question, click here: Upon visiting the site, a video pops up. How can I program the image slides to transition every 7 secon ...

Exploring the world of CouchDB through jQuery and AJAX POST requests while navigating

I am in the process of building a simple web application. Today, I installed Couch 1.3.1 and set up a database. I am currently trying to save a document to my local Couch (localhost:5984) using a POST request from a client browser that is also on localhost ...

Tips for implementing z-index property on table border

I am encountering an issue with an html file that contains a table. The table has one row element with the css property of position: sticky, while the other rows are just example rows with "some text" in each cell. Within column 5 of the regular rows, I h ...