0

I currently have a bit of code with displays a bit of text with an animation and when the user hovers over it audio will play.

However I am adding a feature which will allow the user to change the element type. The code below at the moment changes an element from H1 to P.

It all works except that the script which detects to see if the user has hovered over the element no long seems to work. Which I think is a bit off as the element still keeps the same ID.

Is there a JS reason why the audio script will no longer work or have I missed something obvious?

Thanks!

Before:enter image description here

Detects change

$("#editTextTag").change(function(){
        var id = "#"+$("#editTextId").val();
        var iframe = $('#clientframe');

        var tag = $("#editTextTag").val();

        var element = $(id, iframe.contents());
        var elementcopy = $(element).clone();


        var attrs = { };

        $.each($(element)[0].attributes, function(idx, attr) {
            attrs[attr.nodeName] = attr.nodeValue;
        });


        $(element).replaceWith(function () {
            return $("<p/>", attrs).append($(this).contents());
        });

    });

Currently changes h1 tag to p tag. enter image description here

Hopeless
  • 69
  • 1
  • 7

1 Answers1

1

I think javascript loses the reference to your object when you change or reinsert the object with a different tag name. An easy way around this is to use delegation when assigning your mouseenter action handler.

$('body').on('mouseenter', '#text-1', function(){
// your mouseenter functions
});

Basically, what happens is that when the mouseenter action occurs on a parent element (I chose the body element in this example), it checks to see if the event happens to the element supplied in the second argument ('#text' in this case). As long as your parent element stays on the page, your handler should function even when you destroy/reinsert an element with the same selector.

Alternatively you can use a callback function after your replaceWith function to reassign the mouseenter behavior to your new element.

EDIT: If you provide a working fiddle, we can better help debug your scripts!

Tim Bakkum
  • 73
  • 7
  • Awesome, i'll give it ago and get back to you thank you very much – Hopeless Mar 20 '16 at 18:33
  • Yep it worked thank you very much! Next time I will JS fiddle it, I just had a lot of irreverent code that would of been hard to separate out with it on this example. Marked as answer – Hopeless Mar 20 '16 at 18:40