samedi 8 mai 2021

if image and url contain the same word, can I add a class?

I have an interesting idea, but maybe (or rather hopefully) it isn't new to you.

I have an image-based menu on a homepage. That is, hundreds of images. When the user has browsed to a certain URL, and then opens the dropdown again (containing the images) I want the URLs image to have a frame.

For example, the user is on my-homepage.com/flowers and the image "#flowers" gets a frame from a class.

I know I can do this which works great:

jQuery(function() {
  var loc = window.location.href;
  if(/my-url/.test(loc)) {
    jQuery('#my-image').addClass('active-image-url');
  }
});

.active-image-url {border: 1px solid #000;}

But then again, I have hundreds of images, so it would be quite crazy to add that code a hundred times. Isn't there a way to compare URL and image ID and if these are the same, the class gets added? For example, if a part of the URL my-homepage.com/flowers partly equals "#flowers" please add class.

I know it is not like this, but for the sake of explaining well:

jQuery(function() {
  var loc = window.location.href;
  if(/flowers/.test(loc)) {
    jQuery('#flowers').addClass('active-image-url');
  }
});

What do you think, could it be done? Maybe it's a JavaScript task?

Best regards, Skt

Aucun commentaire:

Enregistrer un commentaire