1

In the past I used the following code to take the take the text in the data-placeholder attribute and use it as a placeholder text for my div.

[contentEditable=true]:empty:not(:focus):before {
    content:attr(data-placeholder)
}

This worked great, but in my current project we need to do the same thing except it's entirely built using jQuery. I know jQuery has .empty(), .before(), :not(), and .focus() functions. With the way the jQuery selectors work, is it possible to use the CSS selector in the jQuery selector like so?

var div = $([contentEditable=true]:empty:not(:focus):before);

If not, then is there a better way to do this when working with so many functions?

19
  • You can't use :before and :after in jQuery. They're not real elements. Commented Sep 25, 2015 at 22:42
  • What are you trying to do? what's the purpose of selecting these elements? Commented Sep 25, 2015 at 22:42
  • @Amit I'm trying to take the CSS above and recreate it using jQuery so that we can continue to use this in our project. Commented Sep 25, 2015 at 22:44
  • Also, jQuery can't automatically react to attribute changes like contenteditable. Commented Sep 25, 2015 at 22:44
  • 1
    I can think of how to do the DOM changes in jQuery, but not how to trigger it. jQuery requires you to put the code in event handlers, but there's no event that happens just because an element is empty and doesn't have the focus. Commented Sep 25, 2015 at 22:50

1 Answer 1

3

Simple solution is to append a style tag:

var rule ='[contentEditable=true]:empty:not(:focus):before {'+
   ' content:attr(data-placeholder)'+
'}';
$('head').append('<style>'+rule +'</style>');
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.