Adjust the color when hovering with the mouse

I want the border color to change to black instead of #FF00FF when hovering over an image. Here's my current JavaScript code:

javascript:for(i=0;i<document.getElementsByTagName('img').length;i++)  
     {
     var imgTag=document.getElementsByTagName('img')[i];   
     imgTag.style.border='5px solid #FF00FF';
     imgTag.title=''; 
     imgTag.onclick=function()
          { 
         return !window.open('http://www.example.com/#/'+this.src);
          }
      }
    void(0)

Any suggestions on how I can achieve this? Thank you. -Frank

Answer №1

To create a dynamic effect on images, you must attach event listeners for the mouseover and mouseout events in order to alter the border color of the image:

const images = document.getElementsByTagName('img');
for(let i = 0; i < images.length; i++) {
    images[i].addEventListener('mouseover', function() {
        this.style.borderColor = '#000';
    });
    images[i].addEventListener('mouseout', function() {
        this.style.borderColor = '#f0f';
    });
}

Take a look at an example here: http://jsfiddle.net/bNk4Y/

Answer №2

Is there a bug in the code you're using? If I understand your question correctly, this solution should work: HTML:

<img src="" >
<img src="">
...

JS:

var imgs = document.getElementsByTagName("img");
for(i=0;i<imgs.length;i++)
{
    imgs[i].onmouseover = function() {this.style.border="1px red solid";};   
}

Keep in mind that achieving the same effect with CSS is preferred for better practice - especially if users have JavaScript disabled.

img:hover {
border: 1px red solid;
}

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

How can I resolve the error message "Uncaught TypeError: Cannot use 'in' operator to search for 'length' in" to successfully display my data?

When I send an ajax request to iterate over multiple arrays, I encounter the following error: Uncaught TypeError: Cannot use 'in' operator to search for 'length' in $.get(url).done(function(data){ var data = JSON.stringify(data); v ...

What is the best way to utilize moment.js for adding days while excluding weekends?

I have a requirement to set a default follow-up date that is two days ahead of the current date. The existing code for this functionality is as follows: const Notify = moment().add(2, 'days').toDate(); Now, I need to modify this code to exclude ...

Switch between selecting every group of 3 items and every group of 4 items

Having an array with more than 14 items, I need to group them into 2 different groups in this specific way: The first 3 (#1,2,3) will be in array A, the next 4 (#4,5,6,7) will be in array B, the following 3 (#8,9,10) will be in array A, the subsequent 4 (# ...

Is there a way to access the initial item in a JavaScript array?

Recently, I've been delving into the world of javascript and encountered a task that involves removing the first item from an array. Solution One function getFirst(arr, item) { arr.push(item); var removed = arr.shift(); return removed; } S ...

No data being displayed or returned from API when using async await

My Ionic 6 + Angular 14 application is currently facing an issue with displaying data retrieved from an API... I have implemented a service to fetch the data from the API and then called this service in the component. The app compiles without any errors a ...

Execute function upon initial user interaction (click for desktop users / tap for mobile users) with the Document Object Model (DOM)

Looking to trigger a function only on the initial interaction with the DOM. Are there any vanilla JavaScript options available? I've brainstormed this approach. Is it on track? window.addEventListener("click", function onFirstTouch() { console.l ...

Node.js is executing the CRON process twice

Within my Node.js application, I have set up a CRON job that runs every day at 10 AM to send push notifications to users. However, I am encountering an issue where two notifications are being sent to the user's device each time the CRON job is trigger ...

What is the best way to include two class names within a single div using Next.js?

Struggling to include two different CSS classes into a single div element, I encountered some issues. For reference, here is a screenshot: https://i.stack.imgur.com/UuCBV.png https://i.stack.imgur.com/sHNwq.png My code snippet looks like this: blog.js ...

What is the best way to integrate nano.uuid into a series of promises that are fetching data from the database?

When working with express routing and nano, I encountered a challenge: router.get('/', function (request, response) { db.view('designdoc', 'bydate', { 'descending': true }) .then(results => { // data ...

What is the correct way to register and utilize props in a newly created Vue custom element?

I have started using the new defineCustomElement feature in Vue version 3.2. Here is an example code snippet from main.js: import { defineCustomElement } from './defineCustomElementWithStyles' import App from './App.ce.vue' ...

Disregard the Field File when utilizing jQuery validation

I have created a form with jQuery validation, but I am facing an issue where the file upload field is showing a message "enter no more than 3 characters." I believe this problem is due to the maxlength="3" property in the file field. How can I remove the ...

transform an array to an array consisting of objects

Below is an array list that needs to be converted into a specific form. var data = [ "USA", "Denmark", "London"]; The desired format for the array is: var data = [ { "id" : 1, "label": "USA" }, { "id" : 2, "label": "Denmark" }, { "id" : 3, "label": " ...

Vue: The enigmatic world of ghost properties?

During my project work, I encountered the following code snippet: Main component - <ParameterModal>: <template> <modal-wrapper props="..."> <!-- ... other similar templates are present... --> <template v-else-if="moda ...

How to Boost SEO with AngularJS by Customizing Meta Descriptions for Every Partial

Imagine a scenario where there are two partial pages - Sign Up ('/signup') and Sign In ('/signin'). For the sign up partial, I want to include this meta tag: <meta name="description" content="Sign Up"> Similarly, for the sign i ...

boosting the maximum number of requests allowed

What can be done to increase the request limit if the user continues to hit rate limits? This is my current rate limiter setup: const Limiter = rateLimit({ windowMs: 10000, max: 5, standardHeaders: true, legacyHeaders: false, keyGenerator: funct ...

Guide to inserting a Link or "a" tag into the dropdown menu choices in React

Currently, I find myself tackling a project involving REACT that is slightly outside my comfort zone. My goal is to create a straightforward dropdown menu that can alter the URL seamlessly. Below is the code snippet: function Front() { const [selectedO ...

Extracting IDs, classes, and elements from a DOM node and converting it into a string format

Can someone please guide me on how to extract the DOM tree string from an element? Let's consider this HTML structure: <div> <ul id="unordered"> <li class="list item">Some Content</li> </u ...

Angular 4 Observables: Triggered Twice Due to Successive Subscribers

Encountering a peculiar issue with Angular 4 Observables. Implemented a ServiceProxy.ts to manage all HTTP calls for the application. @Injectable() export class ServiceProxy { private base_url = 'https://localhost:8443'; ...

Other options for positioning background in SVG or using CSS within SVG could include center center alignment settings

I am currently developing a website where I have a div covered by an SVG. When I use this SVG as a background image and apply background-position: center center, it functions as expected. However, my issue arises when I try to add additional CSS in this ma ...

What exactly is the purpose of editing a host file?

After reviewing this repository, an automatic message pops up: Don't forget to modify your host file 127.0.0.1 * http://localhost:3001 What exactly does that entail? ...