Enhancing User Experience with Image Layers and Interactive Selection through Javascript

Hey there! I'm working on creating a fabric and background gallery for Greek letter apparel in my college town. If you're not familiar with what I mean, take a look at this example of a fabric letter here. The idea is to have customizable foreground and background options that can be easily changed by clicking on a similar image.

So far, here's what I've got:

<script type="text/javascript">// <![CDATA[
function changeImage(filename)
{
document.mainimage.src = filename;
}// ]]></script>

For each fabric, I have the following setup:

<a href="javascript:changeImage('/wp-content/themes/collegiateconnectionbg/images/fabrics/foregrounds/37.jpg')">
<img src="/wp-content/themes/collegiateconnectionbg/images/fabrics/foregrounds/37.jpg"
alt="" width="100px" height="50px" /></a>

I like how this functions for one layer, but I'm looking to add an additional layer while keeping it displayed at the top of the page. I realize I'll need to use Photoshop and transparency for both layers, which is fine, but I want to make sure it's possible before creating hundreds of images.

I know I can manipulate z-index and CSS, but the example I found here didn't work as expected and caused issues with my page layout.

You can check out my tester webpage here to see the current code in action (try clicking on the navy & white stars image to see a rough "A").

Thanks so much for any help you can provide!

Answer №1

Here's a possible fix for your issue.

To see a live demo, visit: http://jsfiddle.net/hM6dj/4/

The solution involves creating images of letters with transparent backgrounds.

Example

Selecting the letter 'A', you'll notice that the area around it is white while the inside remains transparent.

Code

You just need to overlay this transparent image on top of another image. The background will show through the transparent areas, creating a patterned 'A'.

Note: I used data URLs for the foreground letter to avoid hosting the images externally. Learn more about data URLs here.

HTML

<div class='container'>
    <div class='foreground foreground-Black'>&nbsp;</div>
    <div class='background background-Cow'>&nbsp;</div>
</div>

<h2>Foreground Options</h2>
<input type='button' class='btnforeground' data-class='foreground-Black' value="Black" />
<input type='button' class='btnforeground' data-class='foreground-Red' value="Red" />
<input type='button' class='btnforeground' data-class='foreground-Green' value="Green" />

<h2>Background Options</h2>
<input type='button' class='btnbackground' data-class='background-Cow' value="Cow" />
<input type='button' class='btnbackground' data-class='background-Stars' value="Stars" />
<input type='button' class='btnbackground' data-class='background-Dots' value="Dots" />
​

JS

$('input[type="button"].btnforeground').click(function(){
    $('div.container > div.foreground').removeClass().addClass('foreground').addClass($(this).attr('data-class'));
});


$('input[type="button"].btnbackground').click(function(){
    $('div.container > div.background').removeClass().addClass('background').addClass($(this).attr('data-class'));
});
​

CSS

.container{
    position:relative; 
    width: 200px;
    height: 200px;    
}

.foreground, .background{
    width: 200px;
    height: 200px;
    background-repeat: no-repeat;
    position:absolute;
    z-index:100;
}

.background{
    background-repeat:repeat;       
    z-index:50;
}

.background-Cow{
background-image: 
url(http://www.collegiateconnectionbg.com/wp-content/themes/collegiateconnectionbg/images/fabrics/foregrounds/424.jpg);
}

.background-Stars{
background-image: 
url(http://www.collegiateconnectionbg.com/wp-content/themes/collegiateconnectionbg/images/fabrics/foregrounds/48.jpg);
}

.background-Dots{
background-image: 
url(http://www.collegiateconnectionbg.com/wp-content/themes/collegiateconnectionbg/images/fabrics/foregrounds/521.jpg);
}
/* Omitted due to StackOverflow character restrictions.
.foreground-Black{

    background-image: url();
}

.foreground-Green{
    background-image: url();
}

.foreground-Red{
    background-image: url();
}
*/

EDIT

Upon inspection with Google Chrome's Developer tools, there seems to be HTML mixed in with the JavaScript code (notably the paragraph tags <p>, </p>).

It's recommended to wrap jQuery events within a ready function for better organization. The JS Fiddle automatically did this, but here's the updated code snippet:

JS

$(function(){
    $('input[type="button"].btnforeground').click(function(){
        $('div.container > div.foreground').removeClass().addClass('foreground').addClass($(this).attr('data-class'));
    });


    $('input[type="button"].btnbackground').click(function(){
        $('div.container > div.background').removeClass().addClass('background').addClass($(this).attr('data-class'));
    });
});
​

EDIT2

A couple of points to consider:

  1. Your CSS classes:

    • .foreground
    • .background
    • .foreground-Black
    • .foreground-Cow
    • and more...

Most of these classes don't seem to have the properties set as per the example provided. You can directly copy the relevant CSS from the jsfiddle link.

  1. You've named the container class as .viewer but referenced it as .container in your JavaScript. Be sure to align the class names for proper functionality.

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

Choose a new image by confirming your selection with a dialog box

I have a collection of images displayed in a grid, and I want to be able to select one of them to update the value with the chosen image. Before proceeding with the update, I need a confirmation prompt to ensure the user wants to proceed or cancel the acti ...

How can I transfer data to a different component in Angular 11 that is not directly related?

Within the home component, there is a line that reads ...<app-root [message]="hii"> which opens the app-root component. The app-root component has an @input and {{message}} in the HTML is functioning properly. However, instead of opening t ...

Identify if a process operates synchronously or asynchronously

Can you identify in node.js, with the help of a function, if a method is synchronous or asynchronous? I am interested in creating a function that achieves the following: function isSynchronous(methodName) { //check if the method is synchronous, then ...

Using API calls to update component state in React-Redux

I am currently working on setting up a React application where clicking on a map marker in one component triggers the re-rendering of another component on the page. This new component should display data retrieved from a database and update the URL accordi ...

Failed to convert video to blob and upload it due to readAsArrayBuffer returning an empty array

Currently, I am facing an issue while attempting to upload a video using Ionic, Capacitor, and React. To achieve this, I have integrated the cordova-video-capture-plus plugin into my project. The problem arises when I try to execute the readAsArrayBuffer ...

The busboy does not have the ability to receive any uploaded files

My form utilizes ng-flow for managing file uploads: <form class="form-horizontal" enctype="multipart/form-data"> <div flow-init="{target: '/test', testChunks: false, query: {'_csrf': '{{csrf}}', 'somestring& ...

Could you please explain the significance of scope: [variable-name]='@' in Angular?

I absolutely despise asking what may seem like foolish questions, however, it seems that the AngularJS documentation authors have left out some crucial clarifications. When constructing a directive, you have the ability to connect variables within your di ...

What is the best way to set the length of an undefined item in an object to 0 in reactjs?

I am facing a challenge keeping track of scores within each article and displaying them accurately. The issue arises when there is a missing "up" or "down" item in the object. Below is the data containing all the votes: const votes = { "1": { "up": ...

When using AngularJS in conjunction with Karma-Jasmine, it is important to note that the functions verifyNoOutstandingExpectation() and verifyNoOutstandingRequest() may not

There is an unresolved HTTP request that needs to be flushed. When I use the following code afterEach(function(){ $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); The code functions correctly and I ...

Disabling CSS transitions and attempting to alter the style of an HTML element using JavaScript may not consistently work as expected

Currently, I am in the process of creating an animated effect for a website that involves moving two elements' positions over time and resetting them to their original position. Only one element is displayed at a time, and the animation should run smo ...

Is it possible to switch between different fabricJS canvases seamlessly?

Consider this scenario where I have three canvas elements: <canvas id="c1" width="400" height="300"></canvas> <canvas id="c2" width="400" height="300"></canvas> <canvas ...

By enabling sorting on the table, the checkbox gets selected automatically

On this particular webpage, I have a unique setup: Users are presented with the option to move items between two tables using sortable functionality. Each table currently holds only one item. The upper table displays tasks assigned to a worker that remai ...

Present XML data on an HTML page to generate interactive form features

I have an application that features a checkbox tree. I would like to automatically pre-select those checkboxes if the user had previously checked them. To achieve this, I receive XML data from my backend Perl script which contains information on which che ...

Is it possible for CSS to prevent the insertion of spaces?

When filling out a form, I am able to insert spaces in inputs but not in the textarea (which is necessary). Interestingly, inserting spaces in the textarea works flawlessly. <form action="/#wpcf7-f519-o1" method="post" class="wpcf7-form" enctype="mu ...

Enter key not triggering submission in jQuery UI autocomplete field

I'm currently working on implementing the autocomplete feature following a tutorial, and while it's functioning, I'm facing an issue with submitting the form when the user selects an item and hits enter. Below is the Coffeescript code that I ...

The error message "Unable to push property in an undefined array" is displayed when attempting to push a property into

I'm struggling to debug the error message TypeError: Cannot read property 'push' of undefined. The following code snippet is what's causing the problem: const parent_lead_contact = this.props.parentLeads?.filter((lead) => lead. ...

Is it possible to modify the host header within an Angular app?

I'm experiencing a vulnerability issue and to resolve it, I need to utilize SERVER_NAME instead of the Host header. Is it possible to accomplish this using Angular? ...

Display a video modal upon page load, allowing users the option to click a button to reopen the modal

Looking for a way to make a video modal automatically open on page load and allow users to reopen it by clicking a button? Here's a snippet of code that might help you achieve that: HTML <html> <head> <link rel="stylesheet ...

Connecting a picture to a web address using the <img class> tag

I'm facing a major issue with the "fade script" I added to my portfolio. It's designed to fade between thumbnails using jQuery and CSS, but it relies on 2 img classes that I can't seem to link properly. Basically, I want to link the image g ...

Troubleshooting a Codeigniter issue with CSRF and jQuery ajax

Having trouble with posting data using ajax? I keep running into an error related to CSRF and despite my efforts, I have not been able to find a solution. Can someone please assist me with this issue? Here is the error message I am consistently receiving: ...