mariob_452
mariob_452

Reputation: 103

mouseenter mouseleave within contents of iframe

I'm trying to highlight elements within a iframe with no success. I've tried using mouseenter/mouseleave with no success. It does not fire.

$('#iframe').contents().mouseenter(function (e) {
    //var element = $(e.target);
    var element = $(this);

    $(element).addClass("highlight");
}).mouseleave(function (e) {
    $(element).removeClass("highlight");
});

I've had better success with mousemove however it highlights the parents as well which I don't want.

var prevElement;
$('#iframe').contents().find('html').on('mousedown', function (e) {
    e.stoppropagation()
    //e.preventDefault - did not work either
    var element = $(e.target);


    if (prevElement == null) {
        prevElement = element;
        element.addClass("edit-element-selector");
    }
    else {
        if (prevElement != element) {
            prevElement.removeClass("highlight");
            //prevElement.parents().removeClass("highlight"); did not work
            element.addClass("highlight");
        }   
    }
});

HTML

<iframe id="iframe" srcdoc="@Html.Raw(ViewBag.html)"></iframe>

Upvotes: 0

Views: 2606

Answers (3)

mariob_452
mariob_452

Reputation: 103

My problem had 2 issues.

  1. My css was wrong.

    Wrong

    .highlight :hover { 
      outline:4px solid #f00;
    }
    

    Right

    .highlight {  
      outline:4px solid #f00; 
    }
    
  2. Hover was bubbling up to the parents. Mouseenter and mouseleave worked however.

    var $iframe = $("#iframe").contents(); 
    
    $iframe.find('*').mouseover(function (e) {
        $(e.target).addClass('highlight');
    }).mouseout(function (e) {
        $(e.target).removeClass('highlight');
    });
    

Upvotes: 1

mathius1
mathius1

Reputation: 1391

Try jQuery Hover

    $(function () {
        var iContent = $('#iframe').contents();
        iContent.find('#id_username').val("New Value!");
        iContent.find('#id_username').hover(function () {
            $(this).css("border", "1px solid red");
        }, function () {
            $(this).css("border", "1px solid #c4c7cb");
        });
        console.log(iContent.find('#id_username'));
    });

jsFiddle

Sorry I guess I misunderstood the question. Here is an updated fiddle changing the value of a text input and changing border color on hover.

Upvotes: 0

Dom Adams
Dom Adams

Reputation: 281

The css rule for .hover is not visible in the context of the iframe. Either use .css() to set style directly, add the css links or clone all styles in the main document into the iframe with jQuery.

Here is a working jfiddle which you should easily be able to copy.

http://jsfiddle.net/danmana/pMBw2/

Upvotes: 1

Related Questions