What is the best way to incorporate hyperlinks or text color modifications to a variable string in JavaScript?

I have a website that features a random on-load slideshow with text displayed in div containers for each slide. I am looking to enhance the functionality by adding links or changing the color of specific words within the text. You can view my current progress on this JSFIDDLE link: http://jsfiddle.net/shadna/Agq7W/

For your convenience, here is the code snippet:

JavaScript:

jQuery(function($){
    $('#homebanner').css({backgroundColor: "#000"}); 
    var totalCount = 4; 
    var num = Math.ceil( Math.random() * totalCount );
    var hText = ["WE SPEAK ARCHITECTURE", "WE HAVE HIGH SPIRIT(S)",  "STRATEGY: BUILT ON HUMAN-CENTERED", "FOREVER IN BLUE JEANS"];
    var hsubText = ["CLIENT: EDA ARCHITECTS", "CLIENT: HIGH WEST DISTILLERY", "CLIENT: ARCHITECTURAL NEXUS",  "CLIENT: VAULT DENIM"];

    function setBGImage() { 
        var bgimage = 'http://bwpcommunications.com/TESTING/images/homepage/'+num+'.jpg';
        $('#homebanner').css({
            backgroundImage:"url("+bgimage+")",
        }); 
        $('#htxt').html(hText[num - 1]);
        $('#hsubtxt').html(hsubText[num - 1]);
    } 
    setBGImage(); 
});

HTML::

<div id="homebanner">
    <div id="hwrap">
        <div id="htxt"></div>
    <div id="hsubtxt"></div>
    </div>
</div>

I would greatly appreciate any guidance or tips from experienced JavaScript users.

Answer №1

Initially, let's simplify and modify the code:

jQuery(function ($) {
    $('#homebanner').css({
        backgroundColor: "#000"
    });

    // consolidating all information in an array of objects:
    var details = [{
        head: 'WE SPEAK ARCHITECTURE',
        sub: 'EDA ARCHITECTS',
        link: 'http://example.com/edaarchitects.html'
    }, {
        head: 'WE HAVE HIGH SPIRIT(S)',
        sub: 'HIGH WEST DISTILLARY',
        link: 'http://example.com/highwestdistillary.html'
    }, {
        head: 'STRATEGY: BUILT ON HUMAN-CENTERED',
        sub: 'ARCHITECTURAL NEXUS',
        link: 'http://example.com/architecturalnexus.html'
    }, {
        head: 'FOREVER IN BLUE JEANS',
        sub: 'VAULT DENIM',
        link: 'http://example.com/vault-denim.html'
    }],
        // determining upper bounds for random number generation based on details array size:
        num = Math.floor(Math.random() * details.length),

        // storing relevant object for future use:
        item = details[num];

    function setBGImage() {
        // adjusting indexing for images to account for non-zero starting point:
        var bgimage = 'http://bwpcommunications.com/TESTING/images/homepage/' + (num + 1) + '.jpg';
        $('#homebanner').css({
            backgroundImage: "url(" + bgimage + ")",
        });
        $('#htxt').html(item.head);

        // modifying 'sub' text by removing 'CLIENT:' since it is present in all items
        // creating 'a' element using 'link' data from object:
        $('#hsubtxt').html('CLIENT: ' + '<a href="' + item.link + '">' + item.sub + '</a>');
    }
    setBGImage();
});

JS Fiddle example.

Answer №2

Is my understanding correct: You are looking to randomly populate a container with one of your projects?

Here's a simpler suggestion for you:

Create all the containers in HTML without using javascript. Then, based on a random number as an index, show only one of the containers randomly. This approach is much easier and requires less javascript work. There's no need for complex coding!

If you assign a class called .banner to all banners, you can easily target them in JavaScript like this:

$('.banner').eq(yourRandomNumber).css('display', 'block');

Make sure all other banners have display: none.

Also, I noticed in your code that you have multiple IDs for elements with similar styles. It's better to use classes instead and define the properties once. For example:

.banner {
    display:block;
    width:100%;
    height:290px;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    overflow:hidden;
    z-index:700;

You only need separate classes for styles that are different (try to minimize the use of IDs):

.faithologybanner {
    background: url(/TESTING/images/elements/banner_faithology001.jpg) no-repeat center top; 
}

Answer №3

It seems like this is the solution you are looking for (only modifications posted here)

var hsubText = [
    { client : "EDA ARCHITECTS", url : 'http://example.com' },
    { client : "HIGH WEST DISTILLERY",  url : 'http://example.com'},
    { client : "ARCHITECTURAL NEXUS",  url : 'http://example.com' },
    { client : "VAULT DENIM",  url : 'http://example.com' }
];
function setBGImage()
{ 
    var bgimage = 'http://bwpcommunications.com/TESTING/images/homepage/'+num+'.jpg';
    $('#homebanner').css({ 'backgroundImage':'url('+bgimage+')' }); 
    $('#htxt').html(hText[num - 1]);
    var client = hsubText[num - 1].client;
    var url = hsubText[num - 1].url;
    $('#hsubtxt').html('CLIENT : <a href="'+url+'">'+client+'</a>');
 }

CSS:

#hwrap a { color:red }

DEMO.

Revised : (As requested by OP in the commentary)

function setBGImage()
{ 
    var bgimage = 'http://bwpcommunications.com/TESTING/images/homepage/'+num+'.jpg';
    $('#homebanner').css({ 'backgroundImage':'url('+bgimage+')' }); 
    var words = hText[num - 1].split(' ');
    var wordsFirst = words.shift();
    $('#htxt').html($('<span/>', { text:wordsFirst, style:'color:yellow'})).append(' '+ words.join(' '));
    var client = hsubText[num - 1].client;
    var url = hsubText[num - 1].url;
    $('#hsubtxt').html('CLIENT : <a href="'+url+'">'+client+'</a>');
} 

DEMO.

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

Could the absence of a tree view in the div be due to an error in the positioning of the DOM

I'm currently working on displaying a tree structure with specific child elements inside a div using JavaScript and HTML. Despite creating all the necessary objects and ensuring that the data is correctly read from the JSON file (refer to the "data" i ...

Error: undefined property causing inability to convert to lowercase

I am encountering an error that seems to be stemming from the jQuery framework. When I attempt to load a select list on document ready, I keep getting this error without being able to identify the root cause. Interestingly, it works perfectly fine for the ...

"Utilizing jQuery to target all elements within the div class

Here is my current div structure: <div id="gallery-1"></div> <div id="gallery-2"></div> <div id="gallery-3"></div> <div id="gallery-4"></div> <div id="gallery-5"></div> Is there a way to select ...

Troubles with the placement of the navbar icon in responsive design

After following a tutorial on responsive navigation bars (https://www.w3schools.com/howto/howto_js_topnav_responsive.asp), I successfully implemented the navbar on my website. However, I encountered an issue with the icon placement when clicked. Here is ho ...

The functionality of Node.js's hasOwnProperty method fails to return true even for existing properties

When a user logs into my Node.js Express application using Passport, their user object is saved in the request. Here is an example of what the user object may look like: { "uuid": "caa5cb58-ef92-4de5-a419-ef1478b05dad", "first_name": ...

Having trouble incorporating a react component I discovered into my application. Encountering an error message stating "Attempted import error."

My aim is to integrate an existing react component (shown below) that I came across on the internet into my application for use, specifically an animated navigation bar. Upon attempting to compile the code snippets below (snippets 2 and 3), I encountered ...

Creating a clickable table cell in CSS that maintains vertical alignment of text within

Is there a way to make an entire table cell clickable while still vertically aligning the text inside it? One possible solution is to set the link to display:block and adjust the line height. However, this method may not work if the text spans two lines a ...

Creating dual modes (night/day) for your AngularJS application

Currently, I am in the process of developing a project with Angularjs and facing an obstacle with animations. My goal is to implement a feature in my application that allows it to display in two different modes - night mode and day mode. I have come ac ...

What caused the auto resize feature of the Automatic Image Montage jQuery plugin to malfunction?

Apologies in advance if my issue is a bit convoluted. I've integrated the Automatic Image Montage jQuery plugin into a page I'm currently working on. However, I seem to have disrupted the functionality that automatically resizes images when the w ...

Retrieving the value of an inner div upon clicking the outer div

I currently have a collection of button divs, each containing distinct information: <div class="button"> <div id="first"> Johny </div> <div id="second"> Dog </div> <div id="third"> Pasta & ...

The 'length' cannot be searched using the 'in' operator

I am experiencing an issue that I can't quite solve. I have come across solutions for this problem, but they all involve methods that don't use AJAX to retrieve data. If anyone can assist me with this, I would greatly appreciate it. Here is the J ...

Utilizing Angular JavaScript for detecting and setting up JDK installations

I am working on an application that requires the installation of Java JDK. Therefore, I need to develop a detection function for JDK in the system. If it is not found, I plan to install it using a setup provided by me and also set it in the system variabl ...

Looking to remove a row with php, html, and ajax?

Trying to remove a row from an HTML table has been my latest challenge while working with Materialize CSS. Here is what I have so far, where the ID corresponds to the employee ID: https://i.stack.imgur.com/rjwba.png Below is the code snippet: <?php ...

The popover seems to be failing to appear

I am struggling to get a popover to appear when clicking on an appended href element dynamically. Here are the code snippets I have tried: <div id="myPopoverContent"> ...stuff... </div> <div id="div3" style= "width:200px;height:200px;" ...

"Pairing Angular's loader with RxJS combineLatest for seamless data

Hey there! Currently, I'm working on enhancing my Angular application by implementing a global loader feature. This loader should be displayed whenever data is being fetched from my API. To achieve this, I am utilizing ngrx actions such as fetchDataAc ...

How can you open a popover in Ionic from two different triggers but have it appear in the same place?

I am facing an issue with two buttons that trigger the same popover. The problem arises when I click on the second button, a popover is displayed in the wrong place (shown by the big blue plus icon) instead of the right corner (as shown in the second image ...

Creating a custom jQuery tooltip plugin that dynamically follows the mouse's movements - but how can we accurately track the mouse's position?

Hello, I've created 2 functions - one to show a tooltip and another to hide it. These functions can take either ajax configuration or simple configuration. Here's an example: <style type="text/css"> .nube{display:none; height:auto ...

Correcting the reference to "/" (root) for assets after relocating the site to a subdirectory

I currently have a website located in the public_html directory, where all assets (images, css, js, etc) are referenced using /asset_folder/asset. The "/" at the beginning ensures that the browser starts from the root and navigates through the directories. ...

Firefox not displaying caret in Bootstrap dropdown

I am trying to display a caret on the right side of a bootstrap dropdown button inside a button-group. Here is the code snippet I am using: <div class="span3 well"> <div class="btn-group btn-block"> <a class="btn btn-primary dro ...

What is the best way to position elements with CSS?

I need help aligning the arrows and images on the same line. Can anyone guide me on how to do this? (I'm using html5boilerplate). Desired Layout: Current Layout: Existing Code: HTML: <div id="linkbar"> <a><img src="./img/ar ...