Getting the current div id in content-editable div(specific) - javascript

I am recently working on one of my projects and currently i am stuck in some problem. Well, i have made a content editable div where the user can type its input. This content_editable div contains several div's in which user has to type. I tried document.activeElement but it gives me the content_editable div not the specific div and that the one with id second_div
I want to know how to find that specific div in content_editable div where user is type.For example:-
<div contenteditable="true" id="content_editable_div">
<div id="first_div">
I am the first div
</div>
<div id="second_div">
I am the second div and i want to know if the focus is on me
</div>
</div>
My Javascript:
window.onload = function () {
getDivwhohasfocusincontentedtiablediv(); // Something like that
};
I can use jquery but only at the last choice. I want to use only javascript for this purpose.Please help me to solve this, i didn't find solution for this all the net ( it could be that i haven't searched carefully). Thanks in advance

One possible solution is to attach an Event Listener on each inner div to listen for "focus" event. However I found out that not all elements emit "focus" events.
JQuery docs says:
The focus event is sent to an element when it gains focus. This event
is implicitly applicable to a limited set of elements, such as form
elements (input, select, etc.) and links (a href). In recent
browser versions, the event can be extended to include all element
types by explicitly setting the element's tabindex property. An
element can gain focus via keyboard commands, such as the Tab key, or
by mouse clicks on the element.
Adding tabindex attribute to each inner div will make it possible to listen to focus events.
Example at JSFiddle. Note: I wrote the code in JQuery but it can easily be written in JS.

You can find focus element in js using this,
var focused = document.activeElement;

What about this ,
<div contenteditable="true" id="content_editable_div">
<div id="first_div">
First Div
</div>
<div id="second_div">
Second Div
</div>
</div>
$(document).ready(function () {
function onMouseUp(e) {
console.log(this.id);
}
document.getElementById("first_div").addEventListener("mouseup", onMouseUp, false);
document.getElementById("second_div").addEventListener("mouseup", onMouseUp, false);
});
Demo Here JS FIDDLE

to get specific div
in Javascript you can use
document.getElementById("second_div")
or using Jquery
$("#second_div")
make sure your id was unique. This is the fastest way to find obj in any browser.
now for getting getting the active div. why not put specific event whenever the div was clicked or edited. like:
$("#second_div").click (function (){
//raise flag or something
currentDiv = "second_div";
})
function getCurrentDiv()
{
//do something in currentDiv
}
or try also explore other event such as, on mouse over, on mouse leave, etc.
i hope that might help. other wise, please elaborate your question if I missed something.

Related

Javascript - How do I delete the DOM Element by cliking (This command)

I'm trying to delete a DOM element when I click the button.
I assumed that through 'this' I could achieve that easily.
However, 'this' doesn't work in this case.
I tried as below.
deletebutton.addEventListener('click',function()
{this.parentNode.parentNode.removeChild(this.parentNode.parentNode)})
How do I delete the element when I click the DOM Object?
How the page works is
I click the Add Movie button,
and the code reads through the informatin I input
and generates the cards according to the information I put,
Full code is in the following link.
https://codepen.io/jotnajoa/pen/mdVWddz
Thank you in advance
Try replacing your code for this
deletebutton.addEventListener("click", function () {
this.parentNode.remove();
});
Replace
deletebutton.addEventListener('click',function()
{this.parentNode.parentNode.removeChild(this.parentNode.parentNode)})
with
deletebutton.addEventListener('click',function()
{this.parentNode.parentNode.removeChild(this.parentNode)})
I will suggest using selectors rather than hardcoding the element. After that, you can specify it inside the listener that you want to remove that selected element.
The HTML code example:
<div class="cards">
<div id="card-1">
Your card goes here
</div>
</div>
Now as the card is added according to the after the loading of DOM, we will use the concept of Event Delegation to add event listeners. We will all event listener on the parent i.e. cards class, and check if it returns an id.
document.querySelector('.cards').addEventListener('click', event => {
if(event.target.id !== ''){
let storeID = event.target.id;
document.getElementById(storeID).remove();
}
}
This will remove the element from the DOM.
You can rather make use of the getElement or querySelector functions which will allow you to directly access the DOM element in question.

Force a function to overwrite other actions

I am trying to get some contenteditable elements working. Obviously this is incredibly easy with just a simple HTML5 attribute, but I want to be able to toggle the amount of elements with the attribute and also toggle the attribute itself. For example, my starting element is this <article class="column contentEditable"> and then the class of contentEditable is used to toggle the contenteditable attribute. But because I am duplicating this element an amount of times based on what the user selects - I need to run the .focus() action as a function which is then called when some more articles are added. With me so far? Hope so.
Here is the jQuery I have so far (bearing in mind another function sets the class contentEditable to have the attribute contenteditable)
// content edittable
function makeEditable(action){
$('.contentEditable').focus(function(){
$(this).addClass('active');
$(this).prepend('<div class="toolbar" contenteditable="false">TEST</div>');
});
$('.contentEditable').blur(function(){
$(this).removeClass('active');
$(this).remove('.toolbar');
alert('test');
});
}
To a certain extent this works perfectly, however because an article may have already been there when this DOM call was issued before, it means that it's running twice or more (depending on how many times I've changed the option in the select. How on earth can I get the function to only run once per item, i.e. not stack.
Hope this all makes sense, pretty difficult to explain.
I think what's happening here is that you are calling the makeEditable function everytime the user is selecting an element to edit (if I understand your workflow right). If that's happening you're adding a new focus and blur event every time they do and that will cause the event to fire multiple times.
What I recommend is something like this:
function addElement(containerElement) {
// containerElement is a string with the jQuery selector of the parent element
var el = $('<article class="column contentEditable"></article>').appendTo(containerElement);
el.focus(function(){
$(this).addClass('active');
$(this).prepend('<div class="toolbar" contenteditable="false">TEST</div>');
});
el.blur(function(){
$(this).removeClass('active');
$(this).remove('.toolbar');
alert('test');
});
}
function toggleEditable(el) {
// here el is a string with the jQuery selector of the element
$(el).toggleClass('contentEditable');
}
It was a simple case of having a process class on it to only run it once, each time the .focus is run it removes the process class. Pretty simple really, fresh eyes helped after a break. Thanks.

Keypress event on nested content editable (jQuery)

I have a CONTENTEDITABLE div and inside that div I have a CONTENTEDITABLE span, what I want to do is being able to handle the onkeypress event on the inner SPAN.
So, the javascript code would be:
$(function()
{
$('#someid').keypress(function(event){alert('test');});
});
And the HTML content would be:
<div id="mydiv" contenteditable="true">
editable follows:<span id="someid" contenteditable="true">Some TEXT</span>
</div>
If you test it on a browser you'll see you won't see the 'test' dialog when you press a key over Some TEXT, I know the problem is that the event is being triggered in the parent div, so the SPAN doesn't get the event, also because it doesn't have the focus. So I'd like your help to find a solution for this.
The exact code you posted in your question seems to work just fine at http://jsfiddle.net/gaby/TwgkC/3/
Tested and working with FF, Opera, Chrome, Safari, IE8 ..
only change is the removal of the comment which in its current form creates a syntax error.
The #someid need to have focus in order for the keypress to work.
If you want your code to give focus to the element right after creating it, use the .focus() method.
function AppendSpan()
{
$('#mydiv').append('<span id="someid" contenteditable="true">Some TExt</span>');
//Then I want to handle the keypress event on the inserted span
$('#someid').keypress(function(event){
//do something here
alert(this.id);
}).focus();// bring focus to the element once you append it..
}
Update
Two ways to handle this (the fact that there are nested contenteditable elements), not sure if any is acceptable for your case but here they are..
wrap the new contenteditable span in another one, which is set to have contenteditable="false"
(demo: http://jsfiddle.net/gaby/TwgkC/10/)
make #mydiv to not be contenteditable once you add the span..
(demo: http://jsfiddle.net/gaby/TwgkC/11/)
You might be better to bind the keypress event to the #mydiv element like this:
$('#mydiv').delegate("span", "keypress", function(){
console.alert('A key has been pressed: ' + this.id);
});
On further investigation though, it seems that DOM elements such as regular spans and divs are incapable of receiving focus. You may be able to get around this however, by adding a tabindex attribute to each span.

jquery set focus on dynamic content?

In jquery I've appended a <li> element to an unordered list.
How do I focus on the newly created <li> ?
If I do the following:
$("ul").append('<li><input type="text" value="Hi!"></li>');
$("li:last").focus(); //doesn't work because new <li> isn't in dom yet
the focus doesn't work, as noted above.
I know jquery 1.4.2 has a live() event handler which allows you load event handlers to dynamically added elements, but I'm not sure what I'm doing wrong:
$(document).ready(function () {
$('li').live('load', function () {
alert("hi!");
$("li:last").focus();
});
});
You can only set the focus to elements which can hold the focus. By default a list item cannot. This is why your first example fails, not because it isn't in the DOM (it is in the DOM, that is what append does)
In general you should use elements designed to hold the focus (i.e. set the focus on the input not the list item). You can also (but this is less backwards compatible and less logical) use HTML5's tabindex (probably setting it to 0).
onload will not work because list items do not load external content.
You can try this, $(YourElement).trigger("focus").
This is an old post I know, but a simple way to solve this issue is to create a text input in your HTML and set its CSS to "display: none;". On the LI's click event, set the focus in this input and listen to its keypress events.
I've done it and it works like a charm.

Remove 'onclick' command from a child of a div

I am working on a website where I have a main div. I wanted all of the div's page-area to act as a link (clicking on it will cause a submitting of a form and moving to another page) so I added to that div the attribute:
<div class="box1" onclick="javascript:document.forms['womenForm'].submit();" ...>
Everything in this area shuold link to the next page apart from an HTML selection that is inside this div, but should be clickable without moving to the next page.
How can I cause this to happen? I tried to wrap the selected element with a div, giving it href="" or onclick="" but still the form is submitted.
Can anybody resolve this?
You need to stop the bubbling of the event up the hierarchy ...
using the onclick attribute you can do this with
onclick="event.cancelBubble=true;if(event.stopPropagation) event.stopPropagation();return false;" on the select element.
First, the javascript: pseudo-protocol is superfluous in your code because you're using the "onclick" attribute.
I suggest moving away from inline JavaScript and venturing into the more acceptable unobtrusive JavaScript world.
Anyway, what you want to do is check that the event was not fired on a <select> element. With unobtrusive JS that would go something like this:
someElement.onclick = function(e) {
var target = e ? e.target : event.srcElement;
if (!/option|select/i.test(target.nodeName)) {
// do stuff.
}
};

Categories