jQuery-powered one-page site - Information in HTML or JavaScript

I am currently learning JavaScript and jQuery, with a strong grasp on HTML/CSS. I am working on developing a single-page front-end website using Bootstrap for layout design. My main focus now is on implementing functionality. Here is the scenario:

There are 4 <div> elements, each containing text and an image; below them is a <div> with the class #content. Each of the #c1-4 divs has a click listener that triggers a change in the content displayed within the #content div.

<div id="#c1" class="active-div">
    <p>Text Here</p>
    <img src="image.jpg">
</div>

<div id="#c2">
    <p>Text 2 Here</p>
    <img src="image2.jpg">
</div>

<div id="#c3">
    <p>Text 3 Here</p>
    <img src="image3.jpg">
</div>

<div id="#c4">
    <p>Text 4 Here</p>
    <img src="image4.jpg">
</div>

<div id="#content">
    <!-- Content of the selected div goes here -->
</div>

The default selection is #c1 <div>. The content within #content includes text, icons, and images styled appropriately.

The Question: What is the most effective way to store and load content into the #content div? These are the options I am considering based on my current knowledge:

  1. Hard-coding content into the JS file and using .html() to set the content. However, this approach may result in a large amount of HTML code inside the JS file.

  2. Creating separate divs for each of the #c IDs and toggling visibility using .show() and .hide().

  3. Utilizing .load() to fetch content from another HTML document. Concerns include styling issues and potential impact on the display of the #content div.

I would like to understand the advantages and disadvantages of each method, as well as which one would be easier to maintain in the future (e.g., adding more numbered #c divs).

Answer №1

When developers are working on real-world projects, they often rely on backend data to update or add content based on user interactions. The method used to insert this content into a div element - whether it's appending, prepending, using HTML, or loading dynamically - is secondary to the main goal of updating the content. If you're struggling with how to display different content based on user actions, utilizing methods like append and prepend can be helpful in certain situations. Ideally, queries would be made to backend systems such as databases or APIs to retrieve the necessary content. Once obtained, styling the content within div elements using CSS (either inline or through external stylesheets) is crucial for achieving the desired layout. Pay attention to the overall structure and design of your project!

Answer №2

There are numerous methods to achieve this task and various JS frameworks available that approach it differently. However, all of the options at your disposal are suitable in my view, especially since you're utilizing jQuery. Let's delve into discussion about three potential approaches:

  1. You could opt to hard-code the content within your JavaScript. Alternatively, you can embed the content within your HTML using a <script> tag and load it as a JavaScript string in jQuery, similar to how Underscore templates operate.

    <script type="text/template" id="div-1">
        <span>Hello, this is some sample content</span>
    </script>
    

    Later on in your JavaScript code, simply utilize $('#div-1').html() to access its contents, which can then be inserted into your designated content division.

  2. This approach is also entirely viable.
  3. Assuming all CSS styles have already been applied to the document, dynamically altering the DOM will not impact its ability to implement these styles. Just ensure that all styling rules are defined within a pre-loaded stylesheet.

Answer №3

Building upon my previous explanation, I will demonstrate an approach using hidden content divs and dynamically altering HTML with the .html() method.

$(function() {
  var content = $('.active-div .content').html();
  $('#content').html(content);

  $('.item').click(function() {
    $('.item').removeClass('active-div');
    $(this).addClass('active-div');
    content = $('.active-div .content').html();
    $('#content').html(content);
  });
});
.item {
  cursor: pointer;
  display:inline-block;
  padding-right:10px;
}
.content {
  display: none;
}
#content {
  background: #000;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item active-div" id="#c1">
  <p>Text Here</p>
  <img src="image.jpg">
  <div class="content">Sample content 1</div>
</div>

<div class="item" id="#c2">
  <p>Text 2 Here</p>
  <img src="image2.jpg">
  <div class="content">Sample content 2</div>
</div>

<div class="item" id="#c3">
  <p>Text 3 Here</p>
  <img src="image3.jpg">
  <div class="content">Sample content 3</div>
</div>

<div class="item" id="#c4">
  <p>Text 4 Here</p>
  <img src="image4.jpg">
  <div class="content">Sample content 4</div>
</div>

<div id="content">
  <!-- Content of the selected div goes here -->
</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

Issues arise when attempting to include a hyphenated '_' attribute to a tag via the assign method within a function

Currently, I am utilizing a function to dynamically generate input-groups based on the number chosen by the user: const tag = (tag, className, props = {}) => Object.assign(document.createElement(tag), {className, ...props}); Everything is function ...

Encountering an issue such as "Exceeding the maximum number of re-renders. React restricts the amount of renders to avoid

Currently, I am attempting to update the state within the request data method for a string variable as shown below: const ViewChangeRequest = () => { const [requestStageValue, setRequestStage] = useState(''); const { data: request ...

HTML tables tend to have difficulty separating data effectively

Currently, I am encountering an issue while working with a HTML table. I am extracting data from a JSON array: {"key":["1","2","3"],"values":["4","5","6"]}. Instead of placing ...

What is the best way to choose the initial and final <td> that appears within a <tr>?

I am working with an html table that has the following structure: <table> <tbody> <tr> <input type="hidden" name="a" value="x"> <input type="hidden" name="b" value="y"> <td>First Ce ...

What are some alternative ways to position-style anchor elements without using absolute positioning or a wrapping div?

Here is the HTML code snippet that I am working with: <div class="top"> <div class="header title">Some Big Header Goes Here</div> <div class="sub-header title">The fancyness enters here.</div> <a hr ...

AngularJS encountered an error: myFunc has not been defined

I came across a code snippet similar to this one in a Github project, and it seems to be functioning properly. function myFunc($par1, $par2) { //some logic here } angular .module('myApp') .config(['$par1', '$par2' ...

Tips for correctly adding a JSON output to a dropdown menu option

What is the correct way to add JSON results to a select option? Here is a sample of JSON data. AJAX code example: $.ajax({ url: 'sessions.php', type: 'post', datatype: 'json', data: { from: $ ...

Incorporate text inside the border of a Material UI chip

https://i.stack.imgur.com/VATrD.png I'm looking to replicate this design using a pre-built Chip component from MaterialUI While the solution might involve Some Text using html and css, it still may not achieve an identical result. I've come acr ...

Position fixed causing website header to hide behind content

As I work on creating a website for a school, I aim to have a fixed header similar to what can be seen on Facebook. Despite trying out some fixes mentioned in this Stack Overflow [question][1], I am struggling to make it work effectively in my design. The ...

"Utilizing jQuery to present the accurate sequence within a table

https://i.sstatic.net/iCpnO.png I am currently experiencing an issue with my JavaScript code. I am trying to display a single column for "Success/Fail" in a table, but it is showing as two separate columns. The values for the "Success/Fail" column are not ...

Angular 2: Issue with Input Controls losing value within a form element using ngFor

After developing a page in Angular2 that utilizes a form tag and renders input controls using ngFor within a table tag, I encountered an issue where selected input values are removed upon adding a new row. However, everything works fine when the form tag i ...

Assistance Needed with XPATH and CSS for Selenium Automation

Can anyone assist me in finding the appropriate XPATH/CSS locator to extract text from the structure below? <div class="page-header song-wrap"> <div class="art solo-art"> <div class="meta-info"> <h1 class="page-title"> Zehnaseeb I ...

What is the best way to wrap text and move the lines up without affecting the bottom margin?

When the text length increases in the first image, it shifts upwards similar to what you see in this image. How can I achieve this effect? The use of "word-wrap" causes the line to break and move to the next line, which is not what I want. In the code sn ...

I'm just starting to delve into React and I am eager to transform my regular JavaScript code into a React format. However, I am not quite sure how to

In my React JavaScript, I am trying to insert some regular JavaScript code. I attempted to use the {} brackets, but it did not work as expected. import './App.css'; function App() { return ( <> <div className=" ...

The table is refusing to align itself in the center

I've been struggling to center the text inside this table despite trying various solutions. Any help would be greatly appreciated. Here's the HTML code I have: <div id="paccount"> <table style="margin: 0 auto;"> <tr&g ...

I'm encountering some issues with routing within Node.js and Express framework

I have developed a single page application (SPA) using React framework. Currently, I am working on creating an API with Express in Node.js for my app. Below is the code snippet of my server: const express = require('express'); const app = expr ...

Total the values of several items within the array

Here is the data I currently have: const arrayA = [{name:'a', amount: 10, serviceId: '23a', test:'SUCCESS'}, {name:'a', amount: 9, test:'FAIL'}, {name:'b', amount: ...

Error: Unable to iterate through the {(intermediate value)}. It's not a function

Snippet of the original code: const genreOptions = [{{ genreOptions | json_encode | raw }}].map((type , label) => ({value: type, label: label})); Piece of debugging code: const genreOptions = { "Horror": "Kork ...

`finding difficulty in presenting components in react`

I am encountering issues with an outdated version of CRUD where some codes are no longer functioning as expected. Visual Studio Code does not flag them as errors, so the page continues to load but my content box remains empty. Can someone assist me with th ...

Manipulate the text within a canvas element using JavaScript

In this scenario, suppose json.mes represents the received message from Ajax. There is a button implemented to display the message in a canvas box. Although I have attempted to retrieve the message using getElementById (as shown below), it seems to be in ...