0

Im looping through multiple items and setting an image tag like below for each item. Each one has an onmouseover and onmouseout event. The db stores both mouseover and mouseout image directories separated by a semicolon. This part is functioning fine.

<img onmouseover="hover(this, @id);" onmouseout="unhover(this, @id);" src="@(tblIconTable.getSpecificIconFromId(id).icon.Split(';')[0])" />

The issue is when i get to my javascript events

function hover(element, Id) {
    element.setAttribute('src', '@(tblIconTable.getSpecificIconFromId(Id).icon.Split(';')[1])');
}
function unhover(element, Id) {
    element.setAttribute('src', '@(tblIconTable.getSpecificIconFromId(Id).icon.Split(';')[0])');
}

The 'Id' i am using here within more razor within javascript is not being recognized. Is there a clever work around for this?

2
  • 1
    you can’t pass a javascript variable (Id) to .net code like that. by the time hover or unhover is called the first time, those razor variables have already been transformed into a string using whatever value Id had when the .net code was running. Commented Oct 18, 2017 at 17:44
  • James, i know that this solution doesnt work. I was asking for a clever work around Commented Oct 18, 2017 at 17:59

1 Answer 1

1

One way to approach this is by assigning the two urls as data- attributes to each img tag, and then reading those attributes within the hover/unhover functions:

<img onmouseover='hover(this)' onmouseout='unhover(this)' data-img-hover='@(tblIconTable.getSpecificIconFromId(Id).icon.Split(';')[1])' data-img-unhover='@(tblIconTable.getSpecificIconFromId(Id).icon.Split(';')[0])' src='@(tblIconTable.getSpecificIconFromId(Id).icon.Split(';')[0])'>

function hover(element) {
    element.setAttribute('src', element.data('img-hover'));
}
function unhover(element) {
    element.setAttribute('src', element.data('img-unhover'));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.