Use Jquery to place a text in the center of an image

I have images enclosed within <a></a> tags.


        @foreach($themes as $thema)
            <a href="#" data-toggle="modal" data-target="#{{ $thema->id }}">
                <span class="text">{{ $thema->thema }}</span>
                <img src="{{ $thema->picture }}">
            </a>
        @endforeach

Between the <a> and <img> tag, there is a {{ $thema->thema }}. This displays names of topics like Gaming, Health, etc. I have included JQuery code for my images:

<script type="text/javascript>
    $(document).ready(function(){
       $('a img').animate({
            opacity:1
       });
       $('a img').hover(function(){
          $(this).stop().animate({opacity:.5}, 'fast');
       }, function(){
           $(this).stop().animate({opacity:1}, 'fast');
       });
    });
</script>

This effect was inspired by another developer.

Now, I want to display the topic name in the center of the image whenever the mouse hovers over it while keeping the opacity at 50%. I need additional JQuery code or a JavaScript/CSS solution to achieve this.

Prior to this, I used a CSS workaround:

img {
    margin-left: 5px;
    width: 275px;
    height: 228px;
}

.text {
    margin-left: 5px;
    position: absolute;
    color: Black;
    background-color: rgba(255, 255, 255, 0.8);
    width: 275px;
    height: 228px;
    line-height: 228px;
    text-align: center;
    font-family: candara;
    font-size: 24px;
    opacity: 0;
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
    display: inline-block;
}

.text:hover {
    opacity: 0.8;
}

Answer №1

For a demonstration of my solution, I've prepared a snippet using CSS and HTML without JavaScript. This method simplifies maintenance by focusing design concerns in CSS rather than JavaScript for styling and animation.

The vertical centering technique used is a common one explained here. Essentially, the block is absolutely positioned 50% from the top of its container and then shifted up by 50% of its own height using transform: translateY(-50%);.

Feel free to wrap your

<a href="#" data-toggle="modal" data-target="#{{ $thema->id }}">
around the <figure> tags and insert other template variables as needed.

.img-wrapper {
  position: relative;
  display: inline-block;
}
.img {
  /* Adjust dimensions here, everything else should adapt accordingly */
  width: 275px;
  height: 228px;
}
.text-wrapper {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  opacity: 0;
  -webkit-transition: all 0.5s ease;
  -moz-transition: all 0.5s ease;
  -o-transition: all 0.5s ease;
  transition: all 0.5s ease;
}
.text {
  box-sizing: border-box;
  display: block;
  position: absolute;
  padding: 15px;
  top: 50%;
  width: 100%;
  transform: translateY(-50%);
  color: black;
  vertical-align: middle;
  text-align: center;
  font-family: candara;
  font-size: 24px;
}

.img-wrapper:hover .text-wrapper {
  opacity: 0.8;
}
<figure class="img-wrapper">
  <img class="img" src="https://i.sstatic.net/XZ4V5.jpg" />
  <div class="text-wrapper">
    <figcaption class="text">some text</figcaption>
  </div>
</figure>
<figure class="img-wrapper">
  <img class="img" src="https://i.sstatic.net/OVOg3.jpg" />
  <div class="text-wrapper">
    <figcaption class="text">even more text than the last item so you can see how it flows</figcaption>
  </div>
</figure>

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

Angular Bootstrap Popover will now automatically hide after a short period of time due to the removal of the tt_isOpen variable in ui-bootstrap-tpls-0

I recently attempted to implement the ingenious directive created by runTarm for managing angular-bootstrap-popover-hide-after-few-seconds. While using ui-bootstrap 0.11.0.js presented no issues, transitioning to ui-bootstrap-0.12.0 proved problematic as ...

Updating the Django CSRF token within an AJAX prefilter

Here is what I have gathered so far: The view method contains @ensure_csrf_cookie and loads a template. In the template, the csrf token is retrieved from the cookie for a 3rd party api call. The same csrf token is returned from the 3rd party api call. An ...

Position the Mui Card Action at the Upper Right corner

Struggling to align a checkbox within a MUI card to the top right? It has been a challenge for me as well. Here is an image of my current layout https://i.sstatic.net/BwH9o.png. I really want that button to be placed in the top right corner, even when the ...

The request to the controller function in CodeIgniter seems to be malfunctioning

Currently, I am utilizing $.post() to invoke a controller's function directly from the view (although I understand this is considered bad practice). However, when loading a view within that function, it seems to be malfunctioning. Below is the HTML s ...

using css styles in an angular component of a web application

I am currently developing an Angular 2 application with ASP.NET WebAPI 2 to retrieve data. Instead of using ASP.NET cshtml pages, I am utilizing HTML pages to display the content. Within my application project, I have two CSS files - Bootstrap.css and Site ...

Is it possible to utilize the robots.txt file to prevent email addresses from being indexed by search engines?

Within the footer section of my website, there is an email address listed as info@mydomain. I am interested in finding out if there is a way to prevent both harmful and beneficial robots from indexing this particular address. Your assistance is greatly ap ...

What could be the reason behind Express Validator's refusal to accept null values in optional fields?

I have set up express-validator to validate a form, with most fields being optional. The validation for my route looks like this: const ExpValidate = require('express-validator'); router.post('/api/posthandler', [ ExpValidate.body(&quo ...

Tips for programmatically adding/removing rows to a table using ReactJS

I'm currently working on a project where I need to dynamically add and delete rows in a table using ReactJS. However, I've encountered an issue - after adding a few rows, the values in each column become the same even if I change them randomly. ...

I'm having trouble getting a response when trying to use jQuery Ajax to call a JSP on a different port and directory. Can anyone provide guidance on how to properly

On my local server, the HTML file is located at C:/xampp/htdocs/load/index.html and the JSP file is located at C:/xampp/tomcat/webapps/ROOT/jspmysql/load.jsp Here is the code from index.html: ajax({ type:"GET", dataType: 'jsonp', content ...

What is the process for toggling a Bootstrap alert using a button click?

Is there a way to display an alert box multiple times on a web page without the need to refresh it? Currently, when I try to show the alert box again after closing it once, I have to refresh the page. It seems that rendering a bootstrap alert on the page ...

Is it possible to access the grid in ASP.NET Kendoui through code?

When trying to access my grid from Javascript code, I seem to have made mistakes. Can you help me locate them? This is the Grid code I am using: <div id="kendoo"> @(Html.Kendo().Grid<SalePortal.ServiceReference.Product>() .Name("Grid") .Col ...

submitHandler: activating the wrong dialogue box

I've encountered an issue with my submitHandler function while debugging. In Firebug, the error message is displaying correctly based on the true handle in the submitHandler. However, the success dialog is being triggered instead of the error dialog. ...

Unable to prolong jQuery ajax call beyond 4 minutes, despite setting timeout, resulting in net::ERR_EMPTY_RESPONSE error

I have a node.js server up and running, and I am utilizing ajax calls via jquery to interact with the server. One of these ajax calls is anticipated to last approximately 5 minutes. However, every time I make this call, it abruptly times out at exactly 4 m ...

Unable to successfully reset the validity status to true

After implementing server-side validation using the OnBlur event in a form, I encountered an issue where setting the validity of a field to false does not remove the error messages even after setting it back to true. I expected $setValidity true to clear e ...

What potential drawbacks could arise from frequent utilization of setImmediate?

One thing I'm curious about is whether the heavy use of setImmediate can have a negative impact on performance. To illustrate this, I've put together a simple example algorithm. Similar code to this would run every time an HTTP request is made. c ...

Getting rid of unwanted scrollbars in a breeze

I am facing an issue with two nested divs that have the same height settings. The outer div has a max-width/height constraint along with overflow auto, causing scrollbars to appear when the inner content exceeds its dimensions. However, even if I resize ...

Align an image in the center both vertically and horizontally, with a line of text placed directly underneath

I'm currently designing a landing page for one of my clients with their logo placed prominently in the center. Right below the logo, they want their catchy slogan to appear on page load with a fading effect. To achieve this, I have included the slogan ...

Troubleshooting the issue of React forms hook not functioning properly with Material UI Select input

How the Textfield below should load: https://i.sstatic.net/29Sz4.png How it actually loads: https://i.sstatic.net/TdPYM.png My Select component, created using Material UI and React form hook, is not loading the default value as expected. The component ...

Utilizing the Three JS raycaster to detect intersections as the mouse cursor moves around

I have a strong intuition that the current method I am using is completely off base because I am struggling to achieve optimal performance for my website. Take a look at the primary code snippet: onDocumentMouseMove( event ) { if ( this.isUserInterac ...

"Creating a fixed header for a CSS table that remains at the top of

How can I make a table header sticky to the main-1? I have tried creating a working demo with multiple rows but haven't been successful. HTML: on CodePen: https://codepen.io/jokemail/pen/VwBvNBv #printGridHeader { position: s ...