Unable to call a function to retrieve a “value” parameter and replace characters in a string

114
March 07, 2018, at 10:53 PM

There is some code that another developer repeated. I want to put that in a function and then call it but now I am a bit confuse.

This is the code I have:

if(true) {
    $(this).attr('id', function (i, val) {
       return val.replace('Less', 'More');
    }).attr('data-bactmln', function (i, val) {
       return val.replace('Less', 'More')
    });
} else {
    $(this).attr('id', function (i, val) {
       return val.replace('More', 'Less');
    }).attr('data-bactmln', function (i, val) {
       return val.replace('More', 'Less')
    });
}

And I would like to do something like this:

var toggleTealiumId = function(p1, p2) {
    return val.replace(p1, p2);
};
if(true) {
   $(this).attr('id', toggleTealiumId('More', 'Less'));
} else {
   $(this).attr('data-bactmln', toggleTealiumId('Less', 'More'));
}

That val is the value of the string as in the first lines of code, but for now I am getting undefined.

So how can I stop val from being undefined and do it in a proper way?

Any suggestions?

Answer 1

You would need to write it that way:

function toggleTealiumId(p1, p2) {
  return function(i, val) {
    return val.replace(p1, p2);
  }
}

The call toggleTealiumId('More', 'Less') will return a function where p1 and p2 are bound to 'More' and 'Less' (Take a look at How do JavaScript closures work? for more details), this function then can be passed as argument to attr.

READ ALSO
Jquery Click function on <a> not calling URI schemes in href on Android Browser

Jquery Click function on <a> not calling URI schemes in href on Android Browser

I'm trying to redirect users, who are clicking on my facebook article url, to my website page AND if they have my related app on their mobile phone, open the mobile phone app instead

115
removing some empty table details and adding classes and width

removing some empty table details and adding classes and width

I am trying to remove the empty code from table with jquery and add some class to the table tags

106
JS Overlay Menu Not Showing

JS Overlay Menu Not Showing

I would like to display this full screen overlay menu (which works great) on my web page, on the top left hand sideMy code so far can be seen here

156