0

I want to continuously (because the content is received through AJAX) check if a input with a class name of email exists and if exists to show another input with a class name of upload and if this input exists and another input with a class name of button is clicked to do something.

I've managed to continuously check if the input with the class name of email exists and if exists to show the input with the class name of upload, but I don't know how to continue this.

Here is what I have so far:

(function(doc,found) {
var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {

      var mydiv = doc.querySelector("input.email");

      if(found && !mydiv){
        // Was there but is gone, do something
        found = false;
        $('input.upload').hide();

      }

      if(mydiv){
        // Found it, do something
        found = true;
        $('input.upload').show();

      }

    });
});
observer.observe(doc, { childList: true, subtree: true });
})(document,false);
1
  • 1
    why are you mixing jQuery with querySelector calls? Commented May 25, 2016 at 20:35

1 Answer 1

2

You are using jQuery, but also use document.querySelector(). It is better to be consistent and use jQuery all the way, or only use the DOM methods directly without jQuery.

The code for showing/hiding can be made much more concise by using .toggle().

(function(doc) {
    var observer = new MutationObserver(function(mutations) {
        // You don't need to iterate over the mutations, 
        // and showing/hiding the upload input can be done with a one-liner:
        $('input.upload').toggle($("input.email").length>0);
    });
    observer.observe(doc, { childList: true, subtree: true });
    // Here is the click handler. It checks for the existence of the input.
    $('input.button').click(function() {
        if ($('input.email').length) {
            alert('There is an email input. We could do something.');
        } else {
            alert('No email input present');
        }
    });
})(document);

// Simulate a mutation that removes/adds an `input.email` control on button click
$('#toggle').click(function() {
    if ($('input.email').length) {
        $('input.email').remove();
    } else {
        $('<input class="email"  type="text">').insertBefore($('br')[0]);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Email:  <input class="email"  type="text"><br>
Upload: <input class="upload" type="file"><br>
<input class="button" type="button" value="button"><br>
<hr>
Click this button to trigger a mutation concerning email input:<br>
<button id="toggle">Create/Delete email input</button>

Warning about MutationObserver

You have to be careful when listening to MutationObserver events. If in the event handler you make another mutation, a new event will be triggered and you might get into an infinite loop.

Even the above code is risky: the toggle method will change the visibility of an element, which jQuery will do by setting the display CSS style. But that is a modification of the document! And so another mutation event is triggered and the toggle method is called again. Luckily jQuery does not alter the document when it sees that the visibility is already set correctly -- which is the case at that second call -- and so no further mutation events are triggered.

Sign up to request clarification or add additional context in comments.

2 Comments

This is not really working, the "input.upload" it's acting very weird, it appears and disappears at every click and also when the "input.button" is clicked it doesn't work. Maybe because I've added a click method inside the ($('input.email').length) { conditional?
There was indeed a problem with the .toggle($("input.email").length);. It needs to get a boolean type argument, so it should be: toggle($("input.email").length>0);. Corrected now, and I also turned it into a testable snippet. Be careful with what you do in the mutation callback, because if you do a mutation in there (like adding a style to an element), it triggers another mutation callback, and might result in an infinite loop.

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.