apatik
apatik

Reputation: 383

JavaScript Syntax issue to target the correct element

I have a JS function that replaces an element by another with FadeOut / FadeIn animation :

$('.avatar-name span').fadeOut("slow", function() {   /*fade out old file-name*/
    $('.avatar-name').append('<span>'+file.name+'</span>');   /*Add file-name*/
    $('.avatar-name span').hide().fadeIn("slow");
    $('.avatar-name span:first-child').remove();   /*remove old file-name now*/
});

It works great when the target element is the following :

<td class="avatar-name">
    <span><?php if(isset($acc_avatar)) echo $acc_avatar;?></span>
</td>

But when I have an input in the same <td> like this :

<td class="avatar-name">
    <input type="hidden" name="acc-avatar" id="acc-avatar" value="">
    <span><?php if(isset($acc_avatar)) echo $acc_avatar;?></span>
</td>

Then it messes up completly (element being multiplied instead of removed and other weird events). Surely I am missing something but I can't put my finger on it. I'm looking for some help to adapt the JS for the <td> including the input.

Thank you for helping me out !

Upvotes: 0

Views: 44

Answers (2)

Dan Weber
Dan Weber

Reputation: 1237

Here is a snippet to assist.

Just fade out the span, remove old one, append new, fade in new.

You could also just change the text of the span with $('.avatar-name').text("newText");

$('.avatar-name').fadeOut("slow", function() {   /*fade out old file-name*/
    $('.avatar-name span').remove();   /*remove old file-name now*/
    var newSpan = $('.avatar-name').append('<span>NEW SPAN</span>');   /*Add file-name*/
    newSpan.fadeIn("slow");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<table>

  <tr>
  
<td class="avatar-name">
    <input type="hidden" name="acc-avatar" id="acc-avatar" value="Val">
    <span>Original span</span>
</td>
  </tr>
  
  </table>

Upvotes: 1

Barmar
Barmar

Reputation: 782785

When you have an input before the span, the span is no longer the first child (the input is the first child, the span is the second child), so span:first-child doesn't match it. Use :first instead of :first-child.

$('.avatar-name span').fadeOut("slow", function() {   /*fade out old file-name*/
    $('.avatar-name').append('<span>'+file.name+'</span>');   /*Add file-name*/
    $('.avatar-name span').hide().fadeIn("slow");
    $('.avatar-name span:first').remove();   /*remove old file-name now*/
});

Upvotes: 2

Related Questions