select currently focused contenteditable div using jquery - javascript

hi i would like to select the parent div of currently placed cursor in a contenteditable div.
the process is, there are multiple contenteditable div in a page. i'd like to select the div which the caret/ cursor is currently positioned. so that using jquery i could change the css.
following is my html code of the div:
<button id="changer">change color</button>
<div id="container">
<div class="section" contenteditable="true">
<p>this is my editable paragraph</p>
</div>
<div class="section" contenteditable="true">
<p>this is my editable paragraph 2</p>
</div>
</div>
following is my jquery code so far:-
$('#changer').click(function(){
document.activeElement.css({'background':'black'});
});
but this gives me the error :- Uncaught TypeError: undefined is not a function
edit:-
the process is when the user clicks a button a color palette lightbox will appear. on click of any of the color on the color palette. the jquery is going to select the currently focused contenteditable div. and change the css.
i want to know how to select the currently focused contenteditable div using jquery.

So the code below console logs the text inside the contenteditable div which is focused. if you write $(this) inside the event handler it will reference the currently div focused
$('[contenteditable="true"]').focus(function(){
console.log($(this).text()); // for example, do whatever you please here
// you said you want to find the parent div of the element focused
var $parent = $(this).parent();
// now $parent is a reference of the parent div of the focused element
});
The tricky thing is that when the user clicks the button, the contenteditable is not focused anymore. so let's make a variable where we store our last focused contenteditable div , and when the user clicks a button, the changes will be made on that very variable.
like so :
var lastFocused;
$('[contenteditable="true"]').focus(function(){
lastFocused = $(this);
});
$('#changer').on('click', function(){
console.log(lastFocused);
lastFocused.css('background-color', 'red');
})
see codepen : here

So I think what you are trapped is how to get the div[contenteditable] which was focused.
The idea is to store the item when it was trigger by a focus event.
$(function() {
var $focus_item = null;
$('[contenteditable]').focus(function() {
$focus_item = $(this);
});
$('#changer').click(function(){
$focus_item.css({'background':'black'});
});
});

Related

Find the currently focused span element inside an editable div [duplicate]

This question already has an answer here:
How to get the selected element inside a contenteditable element
(1 answer)
Closed 10 months ago.
I have a sample at Finding currently focused span in an editable div.
The editable div i.e. a div having the attribute contenteditable="true", contains 3 different spans with each span wrapped in a div. A user could position the cursor in any one of the three spans. My goal is to find out which span is being edited when user clicks on a span content to start editing or types into it. I would like this to work on desktop or mobile devices.
I tried getting the span using document.activeElement as you can see in my code sample, but it gets the editable div and not the current span. I was looking for a JavaScript solution to this problem.
Question:
How would I get the id of span element whose text is being edited using JavaScript?
Html code
<div id="input" contenteditable="true" onfocus="findCurrentSpan(this)">
<div>
<span id="first">first span</span>
</div>
<div>
<span id="second">second span</span>
</div>
<div>
<span id="third">third span</span>
</div>
</div>
<p id="info" style="color:green">
</p>
Javascript code
function findCurrentSpan(editor) {
var element = document.getElementById("input");
var currentSpan = document.activeElement;
document.getElementById("info").innerHTML = "Active element's id is " + currentSpan.id;
}
The Problem is, that you are going to select the active element from the whole Page, that's why it is called document.activElement.
Have a look a this SO Question Get and set cursor position with contenteditable div
In your example findCurrentSpan(this) this is referring to the function findCurrentSpan() so this.id will have the value input.
<div id="input" contenteditable="true" onfocus="findCurrentSpan(this)">
To solve your problem, I recommend you bind an onfocus event to all of input's children (explanation on how the onfocus event works in javascript).
This is how you select all the span elements inside input:
var children = document.getElementById("input").querySelectorAll('span');
After selecting the elements you want to bind an event to. Use a loop to bind an event to all the elements. As far as I know span doesn't implement a focus state so we will have to use click.
children.forEach(function(e) {
document.getElementById(e.id).addEventListener("click", findCurrentSpan)
})
The code will look like this:
function findCurrentSpan() {
console.log(this.id)
document.getElementById("info").innerHTML = "Active element's id is " + this.id;
}
var children = document.getElementById("input").querySelectorAll('span');
children.forEach(function(e){
document.getElementById(e.id).addEventListener("click", findCurrentSpan)
})

Detect on which element content was entered

I've few div's which are generated dynamically.
I would like to detect inside which div content was entered and then perform some action on the other div's.
For example -
<div class="example"></div>
<div class="example">Some random text</div>
<div class="example"></div>
If I have the above 3 div's and I enter in some content inside the 2nd div, I would like to detect inside which example class div the text was entered and then perform some action on the remainder of the div's, say make the border red or enter in some paragraph tags.
How could I do this using javascript or jquery ?
You can filter out the filled divs and then do your action on the result:
$('.example').filter(function() {
return $(this).text().trim() === '';
}).text('test');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="example"></div>
<div class="example">Some random text</div>
<div class="example"></div>
The above will assign the text test to the empty divs only.
You can use .not() to eliminate the element that triggered the event. I'm not sure how your text that triggers the event gets into the div, so I'll give an example using the click event:
$(document).ready(function() {
$('.example').on('click', function() {
$('.example').not(this).each(function() {
console.log($(this));
//do something with $(this)
});
});
});
(You will need to change 'click' to the appropriate event.)

div and its content toggle

I have the html file like this:
<div id = "aseaza-menu">
<div class ="menu" >Audio,Video </div><br>
<div class ="menu" >Electrocasnice</div><br>
<div class ="menu" >Ingrijire personala</div><br>
<div class ="menu" >PC</div><br>
<div class ="menu" >Tablete,Telefoane</div><br>
</div>
<div id="box">
<table id = "produse">
<tbody>
</tbody>
a div containing more div
and the JavaScript file like this:
$(function(){
$("#aseaza-menu").on('mouseover', function(){
$("#box").slideToggle(600);
});
$("#aseaza-menu").on('mouseout', function(){
$("#box").hide();
});
});
I want once the mouse hover the "aseaza-menu" div, I want it to slide toggle and stop no matter on witch of it's elements my mouse hovers over. But instead it does this: mouse hovers "aseaza-menu" div, "box" div slide Toggles but if I move the mouse over one of its elements like "Audio,Video" the process starts over again(the "box" div hides and slides again). Is there any method apply the slideToggle method on the div and it's content? Sorry for my english,Thanks!
Try this:
// Slidetoggle when hovering over parent and children
$('#aseaza-menu').on('mouseover', function(){
$('#box').slideToggle(600);
});
// When no longer hovering parent div, hide box again
$('#aseaza-menu').on('mouseout', function(){
$('#box').hide();
// But don't hide box when no longer hovering children
}).children().on('mouseout', function(e) {
return false;
});
if you don't want to hide the box when no longer hover children, replace the bottom 3 lines of code with
});
Your question is not very clearly formulated but this is my code based on what I could understand from it.

How do I get a jQuery function to work with specific elements when they have the same class names?

I have sections (divs) with text in it, but when the text is too long I made it so the text "fades" (with css) and displays a "show more" button, which shows the full text for that specific div when clicked. The problem is that it only works for the first div, and I believe it's because they all have the same class and id name. What's the best way to get around that? Here's my code:
HTML:
<div id="fade-container">
<div id="fade-content">
<p>
Long text goes here...
<div class="fade-anchor"><span class="btn-primary round-xl small btn-shadow">Show more</span></div>
</p>
</div>
</div>
Script:
<script>
$('.fade-anchor').click(function(e){
e.preventDefault();
$('#fade-content').css('max-height','none');
$('.fade-anchor').remove();
});
</script>
By the way, info is being fetched from the database in a php while loop.
When the user clicks on .fade-anchor you can use thisto get the element currently selected, you should also use classes instead of ids for multiple elements, like so:
$('.fade-anchor').click(function(e){
e.preventDefault();
$(this).parent('.fade-content').css('max-height','none');
$(this).hide(); // Maybe you should hide instead of removing, in case you want to add a toggle effect later on.
});
You can also check out this jsFiddle with the working version.
Hope it helps.
You can achieve it by e.currentTarget
$('.fade-anchor').click(function(e){
e.preventDefault();
$(e.currentTarget).css('max-height','none');
$('.fade-anchor').remove();});

JQuery How do I make part of a form highlighted when focused?

I have a form which is divided into parts seperated by divs eg:
<form>
<div>
Account Details
</div>
<div>
Personal Details
</div>
<div>
...etctec
</div>
</form>
I want that when someone highlights or focuses on any element within the divs the div in question is highlighted using css. Consider the fact that I have applied a number of handlers to certain input elements on this form.
You could try:
$('input').focus(
function(){
// adds the 'highlight' class to the parent
$(this).closest('div').addClass('highlight');
});
With:
$('input').blur(
function(){
// removes the 'highlight' class from the parent so only one highlight is ever visible.
$(this).closest('div').removeClass('highlight');
});
And define the highlight class in CSS:
.highlight {
background-color: #ffa;
}
JS Fiddle demo, please note that, in the demo, I use fieldsets rather than div to wrap the various label and input elements, but otherwise it's exactly the same principle.
Updated the demo for increased prettiness: Revised JS Fiddle.
Edited in response to question from OP:
Thats great - however theres a little problem with this code i.e that if ever an input within a div loses focus the div is shown as unhighlighted. Is there a way so that a div remains focus until an input element in another div is focused upon which the parent of the focused div would then get highlighted
Yeah, assuming that I've understood you right, that's pretty easy:
$('input').focus(
function() {
$(this)
.closest('form')
.find('.highlight')
.removeClass('highlight');
$(this).closest('fieldset').addClass('highlight');
});
JS Fiddle demo.
$('form > div').delegate('input', 'focus', function() {
$(this).closest('div').addClass('active');
}).delegate('input', 'blur', function() {
$(this).closest('div').removeClass('active');
});
Demo: http://jsfiddle.net/ThiefMaster/fG8Au/
If you want to be sure that only the div right inside the form tag is highlighted, use $(this).closest('form > div').
Create a highlight class in your CSS and try the following jQuery:
$('input, select, textarea').focus (function ()
{
var elem = $(this), container = elem.parents ('div');
container.siblings ().removeClass ('highlight');
container.addClass ('highlight');
})
Try this:
.highlight{background:#ddd}
$('input').focus(function(){
$(this).parent().parent().find('div.highlight').removeClass('highlight');
$(this).parent().addClass('highlight');
});

Categories

Resources