Reputation: 117
I want to add 'onclick' functionality to certain elements. These elements are perfectly targeted with this CSS, setting pointer-events to 'auto':
.custom-collections .o_slideshow .end-group {
pointer-events: auto;
}
.custom-collections > .o_slideshow:first-child,
.custom-collections > .o_slideshow .o_slide[data-id="home_slide"],
.custom-collections > .o_slideshow:last-child {
pointer-events: auto;
}
My javascript currently enables the elements to be dragged (on drag) and previewed (on long touch). Ultimately, I need it only to be previewed.
In the javascript, I include this, to disable drag functionality if 'defaultSlide' is one of the classes:
if (event.target.classList.contains('defaultSlide')) {
// If the slide contains 'defaultSlide', it shouldn't be draggable.
return;
}
How should I append the class defaultSlide
to the elements?
Alternatively, what else could I do, instead of an if class
method, to have my drag-script return immediately?
Normally, I would add the class 'defaultSlide' to these elements in javascript when the elements are first created, but that requires a lot of code in my context of bad legacy code
Upvotes: 1
Views: 114
Reputation: 1074335
If that CSS perfectly targets the elements, you have at least two options:
Element#matches
checks to see if the element you call it on matches the CSS selector you provide. So you could use Element#matches
instead of your class check when you get the event, to see if the element matches those selectors:
var selectors = '.custom-collections .o_slideshow .end-group, ' +
'.custom-collections > .o_slideshow:first-child, ' +
'.custom-collections > .o_slideshow .o_slide[data-id="home_slide"], ' +
'.custom-collections > .o_slideshow:last-child';
if (event.target.matches(selectors)) {
// return;
}
document.querySelectorAll
returns a collection of elements that match the CSS selector you provide. So on page load, you could use querySelectorAll
to get all elements matching those selectors and add the class to them:
var selectors = '.custom-collections .o_slideshow .end-group, ' +
'.custom-collections > .o_slideshow:first-child, ' +
'.custom-collections > .o_slideshow .o_slide[data-id="home_slide"], ' +
'.custom-collections > .o_slideshow:last-child';
document.querySelectorAll(selectors).forEach(function(e) {
e.classList.add("defaultSlide");
});
...and then use your existing code that checks for the class when you get the event.
Side note: The object returned by querySelectorAll
only recently got the forEach
method used above; see this answer for details and workaround for slightly out-of-date browsers.
Upvotes: 3