Simplifying repeated onlick events for different selectors
I have 3 img
elements with ID's. When I click the element, I change the img src
like this
$("#employee").on("click", function(){
var x = $(this);
var y = $(this).attr("src");
if($(this).attr("src") == "images/employee.svg")
{
$(this).attr("src", "images/employee_selected.svg");
}
else
{
$(this).attr("src", "images/employee.svg");
}
});
$("#team").on("click", function(){
var x = $(this);
var y = $(this).attr("src");
if($(this).attr("src") == "images/team.svg")
{
$(this).attr("src", "images/team_selected.svg");
}
else
{
$(this).attr("src", "images/team.svg");
}
});
$("#product").on("click", function(){
var x = $(this);
var y = $(this).attr("src");
if($(this).attr("src") == "images/product.svg")
{
$(this).attr("src", "images/product_selected.svg");
}
else
{
$(this).attr("src", "images/product.svg");
}
});
This code seems to be awfully repetitive and I was wondering if there was a way to do this in a single .on click function
using something like a switch statement.
How could I simplify this into a single statement?
javascript jquery
add a comment |
I have 3 img
elements with ID's. When I click the element, I change the img src
like this
$("#employee").on("click", function(){
var x = $(this);
var y = $(this).attr("src");
if($(this).attr("src") == "images/employee.svg")
{
$(this).attr("src", "images/employee_selected.svg");
}
else
{
$(this).attr("src", "images/employee.svg");
}
});
$("#team").on("click", function(){
var x = $(this);
var y = $(this).attr("src");
if($(this).attr("src") == "images/team.svg")
{
$(this).attr("src", "images/team_selected.svg");
}
else
{
$(this).attr("src", "images/team.svg");
}
});
$("#product").on("click", function(){
var x = $(this);
var y = $(this).attr("src");
if($(this).attr("src") == "images/product.svg")
{
$(this).attr("src", "images/product_selected.svg");
}
else
{
$(this).attr("src", "images/product.svg");
}
});
This code seems to be awfully repetitive and I was wondering if there was a way to do this in a single .on click function
using something like a switch statement.
How could I simplify this into a single statement?
javascript jquery
Combine all the selectors into one. The only difference between all 3 is the image names which are easily resolved from theid
ofthis
– charlietfl
Nov 29 '18 at 0:52
Welcome to Stack Overflow. You may consider giving them each a class name and use that selector instead of the ID selector. Much easier for grouping:$(".className").click(function(e){ });
for example.
– Twisty
Nov 29 '18 at 0:55
add a comment |
I have 3 img
elements with ID's. When I click the element, I change the img src
like this
$("#employee").on("click", function(){
var x = $(this);
var y = $(this).attr("src");
if($(this).attr("src") == "images/employee.svg")
{
$(this).attr("src", "images/employee_selected.svg");
}
else
{
$(this).attr("src", "images/employee.svg");
}
});
$("#team").on("click", function(){
var x = $(this);
var y = $(this).attr("src");
if($(this).attr("src") == "images/team.svg")
{
$(this).attr("src", "images/team_selected.svg");
}
else
{
$(this).attr("src", "images/team.svg");
}
});
$("#product").on("click", function(){
var x = $(this);
var y = $(this).attr("src");
if($(this).attr("src") == "images/product.svg")
{
$(this).attr("src", "images/product_selected.svg");
}
else
{
$(this).attr("src", "images/product.svg");
}
});
This code seems to be awfully repetitive and I was wondering if there was a way to do this in a single .on click function
using something like a switch statement.
How could I simplify this into a single statement?
javascript jquery
I have 3 img
elements with ID's. When I click the element, I change the img src
like this
$("#employee").on("click", function(){
var x = $(this);
var y = $(this).attr("src");
if($(this).attr("src") == "images/employee.svg")
{
$(this).attr("src", "images/employee_selected.svg");
}
else
{
$(this).attr("src", "images/employee.svg");
}
});
$("#team").on("click", function(){
var x = $(this);
var y = $(this).attr("src");
if($(this).attr("src") == "images/team.svg")
{
$(this).attr("src", "images/team_selected.svg");
}
else
{
$(this).attr("src", "images/team.svg");
}
});
$("#product").on("click", function(){
var x = $(this);
var y = $(this).attr("src");
if($(this).attr("src") == "images/product.svg")
{
$(this).attr("src", "images/product_selected.svg");
}
else
{
$(this).attr("src", "images/product.svg");
}
});
This code seems to be awfully repetitive and I was wondering if there was a way to do this in a single .on click function
using something like a switch statement.
How could I simplify this into a single statement?
javascript jquery
javascript jquery
asked Nov 29 '18 at 0:26
JuiceBoxJuiceBox
103
103
Combine all the selectors into one. The only difference between all 3 is the image names which are easily resolved from theid
ofthis
– charlietfl
Nov 29 '18 at 0:52
Welcome to Stack Overflow. You may consider giving them each a class name and use that selector instead of the ID selector. Much easier for grouping:$(".className").click(function(e){ });
for example.
– Twisty
Nov 29 '18 at 0:55
add a comment |
Combine all the selectors into one. The only difference between all 3 is the image names which are easily resolved from theid
ofthis
– charlietfl
Nov 29 '18 at 0:52
Welcome to Stack Overflow. You may consider giving them each a class name and use that selector instead of the ID selector. Much easier for grouping:$(".className").click(function(e){ });
for example.
– Twisty
Nov 29 '18 at 0:55
Combine all the selectors into one. The only difference between all 3 is the image names which are easily resolved from the
id
of this
– charlietfl
Nov 29 '18 at 0:52
Combine all the selectors into one. The only difference between all 3 is the image names which are easily resolved from the
id
of this
– charlietfl
Nov 29 '18 at 0:52
Welcome to Stack Overflow. You may consider giving them each a class name and use that selector instead of the ID selector. Much easier for grouping:
$(".className").click(function(e){ });
for example.– Twisty
Nov 29 '18 at 0:55
Welcome to Stack Overflow. You may consider giving them each a class name and use that selector instead of the ID selector. Much easier for grouping:
$(".className").click(function(e){ });
for example.– Twisty
Nov 29 '18 at 0:55
add a comment |
3 Answers
3
active
oldest
votes
Consider the following code:
$(function() {
$(".svg").on("click", function() {
var x = $(this);
var non = "images/" + x.attr("id") + ".svg";
var sel = "images/" + x.attr("id") + "_selected.svg";
if (x.attr("src").indexOf("_") < 0) {
x.attr("src", sel).toggleClass("selected");
console.log(sel);
} else {
x.attr("src", non).toggleClass("selected");
console.log(non);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<img id="employee" src="images/employee.svg" class="svg image" />
<img id="team" src="images/team.svg" class="svg image" />
<img id="product" src="images/employee.svg" class="svg image" />
</div>
We can extract the SRC
of the element that was clicked and based on a specific condition, perform a specific action. This works for all elements with the class selector, svg
.
Hope that helps.
add a comment |
In case you are OK with collections.
HTML:
<div>
<img id="employee" src="images/employee.svg" class="svg" />
<img id="team" src="images/team.svg" class="svg" />
<img id="product" src="images/product.svg" class="svg" />
</div>
JS:
$(function() {
var images = {
employee : ['images/employee.svg', 'images/employee_selected.svg'],
team : ['images/team.svg', 'images/team_selected.svg'],
product : ['images/product.svg', 'images/product_selected.svg']
};
$(".svg").on("click", function(e) {
e.target.setAttribute("src", ( e.target.getAttribute("src") === images[e.target.id][0] ) ? images[e.target.id][1] : images[e.target.id][0]);
});
});
https://jsfiddle.net/uo7rhnbf/2/
add a comment |
More advanced scenario from my side, but also more flexible.
How to invoke?
toggleElementsOn({
selectors: [ 'body', '.btn1' ],
event: 'mouseover',
keyword: '_add_something_to_image_src_path'
})
Additionally as you can see, event and keyword is configurable.
Implementation:
Vanilla JS
function toggleElementsOn ({ selectors, event = 'click', keyword = '_selected' }) {
/**
* Get elements based on passed selectors
* @param {Array<String>} args
*/
const getElements = args => args.map(elem => document.querySelector(elem))
const elems = getElements(selectors)
elems.forEach(elem => elem.addEventListener(event, (e) => {
e.preventDefault();
const target = e.target;
const matcher = new RegExp(`(${keyword}|[-a-zA-Z0-9]+)(\.[a-z]{3})$`, 'g');
target.src = target.src.replace(matcher, (match, filenameOrPostfix, ext) => {
return filenameOrPostfix === keyword ? ext : `${filenameOrPostfix}${keyword}${ext}`;
});
}));
}
jQuery version
$(document).ready(function () {
function toggleElementsOn ({ selectors, event = 'click', keyword = '_selected' }) {
/**
* Get elements based on passed selectors
* @param {Array<String>} args
*/
const getElements = args => $.map(args, elem => $(elem))
const elems = getElements(selectors)
$.each(elems, (key, elem) => {
$(elem).on(event, (e) => {
e.preventDefault();
const target = $(this);
const matcher = new RegExp(`(${keyword}|[-a-zA-Z0-9]+)(\.[a-z]{3})$`, 'g');
target.attr('src', target.attr('src').replace(matcher, (match, filenameOrPostfix, ext) => {
return filenameOrPostfix === keyword ? ext : `${filenameOrPostfix}${keyword}${ext}`;
}));
})
});
}
});
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53530113%2fsimplifying-repeated-onlick-events-for-different-selectors%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
Consider the following code:
$(function() {
$(".svg").on("click", function() {
var x = $(this);
var non = "images/" + x.attr("id") + ".svg";
var sel = "images/" + x.attr("id") + "_selected.svg";
if (x.attr("src").indexOf("_") < 0) {
x.attr("src", sel).toggleClass("selected");
console.log(sel);
} else {
x.attr("src", non).toggleClass("selected");
console.log(non);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<img id="employee" src="images/employee.svg" class="svg image" />
<img id="team" src="images/team.svg" class="svg image" />
<img id="product" src="images/employee.svg" class="svg image" />
</div>
We can extract the SRC
of the element that was clicked and based on a specific condition, perform a specific action. This works for all elements with the class selector, svg
.
Hope that helps.
add a comment |
Consider the following code:
$(function() {
$(".svg").on("click", function() {
var x = $(this);
var non = "images/" + x.attr("id") + ".svg";
var sel = "images/" + x.attr("id") + "_selected.svg";
if (x.attr("src").indexOf("_") < 0) {
x.attr("src", sel).toggleClass("selected");
console.log(sel);
} else {
x.attr("src", non).toggleClass("selected");
console.log(non);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<img id="employee" src="images/employee.svg" class="svg image" />
<img id="team" src="images/team.svg" class="svg image" />
<img id="product" src="images/employee.svg" class="svg image" />
</div>
We can extract the SRC
of the element that was clicked and based on a specific condition, perform a specific action. This works for all elements with the class selector, svg
.
Hope that helps.
add a comment |
Consider the following code:
$(function() {
$(".svg").on("click", function() {
var x = $(this);
var non = "images/" + x.attr("id") + ".svg";
var sel = "images/" + x.attr("id") + "_selected.svg";
if (x.attr("src").indexOf("_") < 0) {
x.attr("src", sel).toggleClass("selected");
console.log(sel);
} else {
x.attr("src", non).toggleClass("selected");
console.log(non);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<img id="employee" src="images/employee.svg" class="svg image" />
<img id="team" src="images/team.svg" class="svg image" />
<img id="product" src="images/employee.svg" class="svg image" />
</div>
We can extract the SRC
of the element that was clicked and based on a specific condition, perform a specific action. This works for all elements with the class selector, svg
.
Hope that helps.
Consider the following code:
$(function() {
$(".svg").on("click", function() {
var x = $(this);
var non = "images/" + x.attr("id") + ".svg";
var sel = "images/" + x.attr("id") + "_selected.svg";
if (x.attr("src").indexOf("_") < 0) {
x.attr("src", sel).toggleClass("selected");
console.log(sel);
} else {
x.attr("src", non).toggleClass("selected");
console.log(non);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<img id="employee" src="images/employee.svg" class="svg image" />
<img id="team" src="images/team.svg" class="svg image" />
<img id="product" src="images/employee.svg" class="svg image" />
</div>
We can extract the SRC
of the element that was clicked and based on a specific condition, perform a specific action. This works for all elements with the class selector, svg
.
Hope that helps.
$(function() {
$(".svg").on("click", function() {
var x = $(this);
var non = "images/" + x.attr("id") + ".svg";
var sel = "images/" + x.attr("id") + "_selected.svg";
if (x.attr("src").indexOf("_") < 0) {
x.attr("src", sel).toggleClass("selected");
console.log(sel);
} else {
x.attr("src", non).toggleClass("selected");
console.log(non);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<img id="employee" src="images/employee.svg" class="svg image" />
<img id="team" src="images/team.svg" class="svg image" />
<img id="product" src="images/employee.svg" class="svg image" />
</div>
$(function() {
$(".svg").on("click", function() {
var x = $(this);
var non = "images/" + x.attr("id") + ".svg";
var sel = "images/" + x.attr("id") + "_selected.svg";
if (x.attr("src").indexOf("_") < 0) {
x.attr("src", sel).toggleClass("selected");
console.log(sel);
} else {
x.attr("src", non).toggleClass("selected");
console.log(non);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<img id="employee" src="images/employee.svg" class="svg image" />
<img id="team" src="images/team.svg" class="svg image" />
<img id="product" src="images/employee.svg" class="svg image" />
</div>
answered Nov 29 '18 at 1:07
TwistyTwisty
14.5k11635
14.5k11635
add a comment |
add a comment |
In case you are OK with collections.
HTML:
<div>
<img id="employee" src="images/employee.svg" class="svg" />
<img id="team" src="images/team.svg" class="svg" />
<img id="product" src="images/product.svg" class="svg" />
</div>
JS:
$(function() {
var images = {
employee : ['images/employee.svg', 'images/employee_selected.svg'],
team : ['images/team.svg', 'images/team_selected.svg'],
product : ['images/product.svg', 'images/product_selected.svg']
};
$(".svg").on("click", function(e) {
e.target.setAttribute("src", ( e.target.getAttribute("src") === images[e.target.id][0] ) ? images[e.target.id][1] : images[e.target.id][0]);
});
});
https://jsfiddle.net/uo7rhnbf/2/
add a comment |
In case you are OK with collections.
HTML:
<div>
<img id="employee" src="images/employee.svg" class="svg" />
<img id="team" src="images/team.svg" class="svg" />
<img id="product" src="images/product.svg" class="svg" />
</div>
JS:
$(function() {
var images = {
employee : ['images/employee.svg', 'images/employee_selected.svg'],
team : ['images/team.svg', 'images/team_selected.svg'],
product : ['images/product.svg', 'images/product_selected.svg']
};
$(".svg").on("click", function(e) {
e.target.setAttribute("src", ( e.target.getAttribute("src") === images[e.target.id][0] ) ? images[e.target.id][1] : images[e.target.id][0]);
});
});
https://jsfiddle.net/uo7rhnbf/2/
add a comment |
In case you are OK with collections.
HTML:
<div>
<img id="employee" src="images/employee.svg" class="svg" />
<img id="team" src="images/team.svg" class="svg" />
<img id="product" src="images/product.svg" class="svg" />
</div>
JS:
$(function() {
var images = {
employee : ['images/employee.svg', 'images/employee_selected.svg'],
team : ['images/team.svg', 'images/team_selected.svg'],
product : ['images/product.svg', 'images/product_selected.svg']
};
$(".svg").on("click", function(e) {
e.target.setAttribute("src", ( e.target.getAttribute("src") === images[e.target.id][0] ) ? images[e.target.id][1] : images[e.target.id][0]);
});
});
https://jsfiddle.net/uo7rhnbf/2/
In case you are OK with collections.
HTML:
<div>
<img id="employee" src="images/employee.svg" class="svg" />
<img id="team" src="images/team.svg" class="svg" />
<img id="product" src="images/product.svg" class="svg" />
</div>
JS:
$(function() {
var images = {
employee : ['images/employee.svg', 'images/employee_selected.svg'],
team : ['images/team.svg', 'images/team_selected.svg'],
product : ['images/product.svg', 'images/product_selected.svg']
};
$(".svg").on("click", function(e) {
e.target.setAttribute("src", ( e.target.getAttribute("src") === images[e.target.id][0] ) ? images[e.target.id][1] : images[e.target.id][0]);
});
});
https://jsfiddle.net/uo7rhnbf/2/
answered Nov 29 '18 at 2:28
Denis KovzelyukDenis Kovzelyuk
966
966
add a comment |
add a comment |
More advanced scenario from my side, but also more flexible.
How to invoke?
toggleElementsOn({
selectors: [ 'body', '.btn1' ],
event: 'mouseover',
keyword: '_add_something_to_image_src_path'
})
Additionally as you can see, event and keyword is configurable.
Implementation:
Vanilla JS
function toggleElementsOn ({ selectors, event = 'click', keyword = '_selected' }) {
/**
* Get elements based on passed selectors
* @param {Array<String>} args
*/
const getElements = args => args.map(elem => document.querySelector(elem))
const elems = getElements(selectors)
elems.forEach(elem => elem.addEventListener(event, (e) => {
e.preventDefault();
const target = e.target;
const matcher = new RegExp(`(${keyword}|[-a-zA-Z0-9]+)(\.[a-z]{3})$`, 'g');
target.src = target.src.replace(matcher, (match, filenameOrPostfix, ext) => {
return filenameOrPostfix === keyword ? ext : `${filenameOrPostfix}${keyword}${ext}`;
});
}));
}
jQuery version
$(document).ready(function () {
function toggleElementsOn ({ selectors, event = 'click', keyword = '_selected' }) {
/**
* Get elements based on passed selectors
* @param {Array<String>} args
*/
const getElements = args => $.map(args, elem => $(elem))
const elems = getElements(selectors)
$.each(elems, (key, elem) => {
$(elem).on(event, (e) => {
e.preventDefault();
const target = $(this);
const matcher = new RegExp(`(${keyword}|[-a-zA-Z0-9]+)(\.[a-z]{3})$`, 'g');
target.attr('src', target.attr('src').replace(matcher, (match, filenameOrPostfix, ext) => {
return filenameOrPostfix === keyword ? ext : `${filenameOrPostfix}${keyword}${ext}`;
}));
})
});
}
});
add a comment |
More advanced scenario from my side, but also more flexible.
How to invoke?
toggleElementsOn({
selectors: [ 'body', '.btn1' ],
event: 'mouseover',
keyword: '_add_something_to_image_src_path'
})
Additionally as you can see, event and keyword is configurable.
Implementation:
Vanilla JS
function toggleElementsOn ({ selectors, event = 'click', keyword = '_selected' }) {
/**
* Get elements based on passed selectors
* @param {Array<String>} args
*/
const getElements = args => args.map(elem => document.querySelector(elem))
const elems = getElements(selectors)
elems.forEach(elem => elem.addEventListener(event, (e) => {
e.preventDefault();
const target = e.target;
const matcher = new RegExp(`(${keyword}|[-a-zA-Z0-9]+)(\.[a-z]{3})$`, 'g');
target.src = target.src.replace(matcher, (match, filenameOrPostfix, ext) => {
return filenameOrPostfix === keyword ? ext : `${filenameOrPostfix}${keyword}${ext}`;
});
}));
}
jQuery version
$(document).ready(function () {
function toggleElementsOn ({ selectors, event = 'click', keyword = '_selected' }) {
/**
* Get elements based on passed selectors
* @param {Array<String>} args
*/
const getElements = args => $.map(args, elem => $(elem))
const elems = getElements(selectors)
$.each(elems, (key, elem) => {
$(elem).on(event, (e) => {
e.preventDefault();
const target = $(this);
const matcher = new RegExp(`(${keyword}|[-a-zA-Z0-9]+)(\.[a-z]{3})$`, 'g');
target.attr('src', target.attr('src').replace(matcher, (match, filenameOrPostfix, ext) => {
return filenameOrPostfix === keyword ? ext : `${filenameOrPostfix}${keyword}${ext}`;
}));
})
});
}
});
add a comment |
More advanced scenario from my side, but also more flexible.
How to invoke?
toggleElementsOn({
selectors: [ 'body', '.btn1' ],
event: 'mouseover',
keyword: '_add_something_to_image_src_path'
})
Additionally as you can see, event and keyword is configurable.
Implementation:
Vanilla JS
function toggleElementsOn ({ selectors, event = 'click', keyword = '_selected' }) {
/**
* Get elements based on passed selectors
* @param {Array<String>} args
*/
const getElements = args => args.map(elem => document.querySelector(elem))
const elems = getElements(selectors)
elems.forEach(elem => elem.addEventListener(event, (e) => {
e.preventDefault();
const target = e.target;
const matcher = new RegExp(`(${keyword}|[-a-zA-Z0-9]+)(\.[a-z]{3})$`, 'g');
target.src = target.src.replace(matcher, (match, filenameOrPostfix, ext) => {
return filenameOrPostfix === keyword ? ext : `${filenameOrPostfix}${keyword}${ext}`;
});
}));
}
jQuery version
$(document).ready(function () {
function toggleElementsOn ({ selectors, event = 'click', keyword = '_selected' }) {
/**
* Get elements based on passed selectors
* @param {Array<String>} args
*/
const getElements = args => $.map(args, elem => $(elem))
const elems = getElements(selectors)
$.each(elems, (key, elem) => {
$(elem).on(event, (e) => {
e.preventDefault();
const target = $(this);
const matcher = new RegExp(`(${keyword}|[-a-zA-Z0-9]+)(\.[a-z]{3})$`, 'g');
target.attr('src', target.attr('src').replace(matcher, (match, filenameOrPostfix, ext) => {
return filenameOrPostfix === keyword ? ext : `${filenameOrPostfix}${keyword}${ext}`;
}));
})
});
}
});
More advanced scenario from my side, but also more flexible.
How to invoke?
toggleElementsOn({
selectors: [ 'body', '.btn1' ],
event: 'mouseover',
keyword: '_add_something_to_image_src_path'
})
Additionally as you can see, event and keyword is configurable.
Implementation:
Vanilla JS
function toggleElementsOn ({ selectors, event = 'click', keyword = '_selected' }) {
/**
* Get elements based on passed selectors
* @param {Array<String>} args
*/
const getElements = args => args.map(elem => document.querySelector(elem))
const elems = getElements(selectors)
elems.forEach(elem => elem.addEventListener(event, (e) => {
e.preventDefault();
const target = e.target;
const matcher = new RegExp(`(${keyword}|[-a-zA-Z0-9]+)(\.[a-z]{3})$`, 'g');
target.src = target.src.replace(matcher, (match, filenameOrPostfix, ext) => {
return filenameOrPostfix === keyword ? ext : `${filenameOrPostfix}${keyword}${ext}`;
});
}));
}
jQuery version
$(document).ready(function () {
function toggleElementsOn ({ selectors, event = 'click', keyword = '_selected' }) {
/**
* Get elements based on passed selectors
* @param {Array<String>} args
*/
const getElements = args => $.map(args, elem => $(elem))
const elems = getElements(selectors)
$.each(elems, (key, elem) => {
$(elem).on(event, (e) => {
e.preventDefault();
const target = $(this);
const matcher = new RegExp(`(${keyword}|[-a-zA-Z0-9]+)(\.[a-z]{3})$`, 'g');
target.attr('src', target.attr('src').replace(matcher, (match, filenameOrPostfix, ext) => {
return filenameOrPostfix === keyword ? ext : `${filenameOrPostfix}${keyword}${ext}`;
}));
})
});
}
});
answered Nov 29 '18 at 4:58
baartkobaartko
47114
47114
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53530113%2fsimplifying-repeated-onlick-events-for-different-selectors%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Combine all the selectors into one. The only difference between all 3 is the image names which are easily resolved from the
id
ofthis
– charlietfl
Nov 29 '18 at 0:52
Welcome to Stack Overflow. You may consider giving them each a class name and use that selector instead of the ID selector. Much easier for grouping:
$(".className").click(function(e){ });
for example.– Twisty
Nov 29 '18 at 0:55