Focus ContentEditable div - javascript

I want to focus the contenteditable div, so that I can automatically start typing when it is inserted into the DOM
I have tried $('.content').focus(), but this does not work
Example html:
<div class="content" contenteditable="true">sample input</div>

I think you probably just need to wrap your code in a window.load function:
$(window).on("load",function(){
$('.content').focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="content" contenteditable="true">sample input</div>
(fiddle: http://jsfiddle.net/hxeqm541/)
What this does is, it waits until the page is fully loaded, before it executes the code inside the window.load.
If you don't do this, the code to focus on the div will be executed before the div even exists on the page, which is impossible. By the time the div finally does exist on the page, the code has already run, so nothing will happen anymore.
Side notes:
Because you reference the div by its class ($('.content')), if you have more than one of these divs with the same class-name, only the last one will receive focus. See example.
You DO NOT NEED to wrap every individual code block in an window.load.
Usually, you can wrap your ENTIRE JavaScript code in the window.load. There might be a few exceptions to that rule, read this and this to fully understand the workings of the window.load mechanism so you'll know exactly how to use it.
(Notice in the second link that .load can also be used on other elements.)

Related

use a javascript variable in inline CSS

I want to do the following:
<div id="theDiv" style="width: aJavascriptVariableOrFunctionCallToGetValue">TESING</div>
I don't want to use, elsewhere in the code,
document.getElementById('theDiv').style.width = someValue;
I actually want that div, when it first appears, to have a width set, inline, by either a JavaScript variable or by way of a call to a JavaScript function.
How can I do this?
This is impossible to do the way you see this.
Every time the variable changes, you need to update the style of that particular object:
var theDiv = document.getElementById("theDiv");
document.getElementById('theDiv').style.width = someValue;
I really don't understand what you mean that when it first appears you want it's width to be set to certain width - why do you want to do that inline? Why can't you just set the width in your Javascript? What's preventing you from doing that? Especially if you want to do it just once and don't want to change it dynamically.
If you want to link the width of the div to a variable, look at frameworks like Backbone or EmberJS. You can then define a renderer that changes the width when the variable changes.
The only way to get JavaScript to run when an element first appears is with an onload event handler. And onload events only work on a few specific elements, like body, script or img.
Here is how you could make it work in your case, with a img tag:
<div id="theDiv">
TESING
<img style="display:none;" src="tinyImage.jpg" onload="this.parentNode.style.width='100px';"/>
</div>
Honestly, I don't see this as a good practice, and I would recommend to just be patient, and set the width later in a script.
Live demo: http://jsfiddle.net/HKW6b/
You cannot do it like that. There are other ways to achieve what you want, though.
Server side processing, specially if the technology you use supports templating. You can manipulate the html value before sending it to the client;
jQuery may be something to consider. Simply fetch the element and use its API. Example:
$("#theDiv").width(aJavascriptVariableOrFunctionCallToGetValue);
This small piece of code does exactly what you want. It is not written inside the element itself, and it is about equivalent to the sample you provided, but again, it's something to consider should you have to do more complex operations on the DOM later on.
If you want to execute that piece of code only once, and after the page is ready, you can do it like this:
var div = $("#theDiv");
div.ready(function () {
div.width(aJavascriptVariableOrFunctionCallToGetValue);
});
The solution for this issue allowed me to set the proper width of the div immediately, asymptotically approaching inlined-javascript as possible, as per one of the comments above suggested:
"If you need the style applied immediately, you can embed a script immediately following your HTML markup and then you won't have the flash of unstyled content I'm guessing you want to avoid. – Harvey A. Ramer"
This solved the 'slow server' => FOUC problem. I added a 'script' tag immediately after the div tag to set the div to the window.innerWidth, problem solved.
From what I've seen, this approach is the earliest/soonest/fastest way to use javascript to set a CSS style attribute -- and it avoids having to code up an 'onload' handler.
The problem with 'onload' handlers being used to set UI style attributes on the page is -- the onload Javascript handler function can grow...and grow...and grow over time over the project's lifespan and you eventually are forced to clean out the onload handler. Best approach is to never use an onload handler that sets styles in the first place.
I'm using React, and this syntax worked for me:
<div id="theDiv" style={`width: ${aJavascriptVariable} %`}>TESING'</div>

how to toggle a div on click at different div?

I am trying to toggle a div by clicking on a different div. The only relation that two divs share is that they are inside the same div. I have a DIV class comment which holds DIV class button that is supposed to toggle DIV class box when clicked. The box DIV is also inside the comment DIV. I am trying to use jQuery(this).find(".box").toggle();, but it is not working. I am triggering it with $( ".button" ).click(function(). The script is currently at the bottom of my body.
Could anyone please tell me what am I doing wrong here? I've been playing around with the function for a while now, but with no luck at all. Thank you in advance for your replies.
JSFIDDLE here
HTML
<div class="comment">
<div class="button">
show/hide .box with text1
</div>
<div class="box">
text 1
</div>
</div>
<div class="comment">
<div class="button">
show/hide .box with text2
</div>
<div class="box">
text 2
</div>
<div>
jQuery
$( ".button" ).click(function() {
jQuery(this).find(".box").toggle();
});
You can use the jQuery selector .siblings() to re-write your function like this:
$( ".button" ).click(function() {
$(this).siblings().toggle();
});
Here's a working fiddle to demonstrate.
All you really need to do is this:
$(this).parent().find(".box").toggle();
In short, change:
jQuery(this).find(".box").toggle();
To ONE of the following lines:
$(this).parent('.comment').find(".box").toggle();
$(this).closest('.comment').find(".box").toggle();
$(this).siblings(".box").toggle();
Full Explanation:
The reason it's not working is due to the call. Let's break down your call and see what exactly it's doing.
First we see a simple jQuery selector. This tells jQuery to look for a div containing the class button. Keep in mind, jQuery makes use of any CSS selector. So selecting an item in jQuery is as simple as using it's CSS selector!
$( ".button" )
Next you are assigning an event. In this case, that event is click, meaning you're telling a div having the class button to do something every time it is clicked. Keep in mind, however, not including a callback function is an easy way to trigger this event as well.
$( ".button" ).click(function() {
Now this next line is where your mistake takes place.
jQuery(this).find(".box").toggle();
The first mistake is the use of jQuery. after you're already making use of it's short sign, $. You only need use the elongated name if you are using jQuery's noconflict because another JS library you include might use $. In other words, if $('.button') works and is a jQuery object when used, then you don't need to use jQuery.. See more about this here.
Now, that aside, we can look at jQuery(this) as $(this). Whenever you use $(this) in an Event's callback method, you're referring to the element that the event was tied too. That means that $(this) in your function refers to $('.button'). The problem here is that you then want it to find an inner element containing the class box. Well according to your HTML, that can't happen since .box is a sibling, it is not within the inner HTML of .button. Thus you need to make a different call before you can find .box.
There are actually several solutions here. No solution is more "correct" than another, just simply different and possibly causes a different amount of "time" to run. Now I went with what I saw as being the most simple in that it gives you control over the parent element which contains ALL relevant elements to this function. I'll talk about possible alternatives in a minute.
$(this).closest('.comment')
The above line simply tells .button:clicked to look for the first parent element that contains the class .comment. In other words, this won't find any children or siblings, it will only go up from the current element. This allows us to grab the block that contains all relevant elements and information and thus make maneuvers as needed. So, in the future, you might even use this as a variable in the function, such as:
$('.button').click(function(e) {
var container = $(this).closest('.comment');
Now you can find anything within this element block. In this case you want to find box and toggle it. Thus:
$(this).closest('.comment').find(".box").toggle();
// Or with our variable I showed you
container.find(".box").toggle();
Now, there are plenty of alternatives based on your HTML layout. This example I've given would be good even if .box was buried inside more elements inside .comment, however, given your exact HTML, we see that .button and .box are siblings. This means that you could make this call different entirely and get the same result using something like:
$(this).siblings(".box").toggle();
This will allow our currently clicked and selected button element to look for ANY and ALL siblings having class box. This is a great solution and simple if your HTML is that simple.
However, many times, for "comment" type setups, our HTML is not so simple, nor is it static. It's usually something loaded after the page load. This means our general assignment of .click will not work. Given your exact HTML and not knowing a static Parent ID, I would probably write your code as:
$(document).on('click', '.button', function(e) {
$(this).siblings('.box').toggle();
});
What this does is allow for this click event to be assigned to ANY element containing .button for a class, whether loaded with page or even ten minutes after the page is up. However, the caveat often seen here is the assignment is placed on document. Should we assign a lot of events to document it could become quite convoluted and possibly slow down the client's browser. Not to mention the arguments held over all the other headaches this could cause. So here's my recommendation, make a static (loads with page, is a part of page's main HTML) loading area and do our dynamic assignment to that. For instance:
<div id"Comments"><!-- load comments --></div>
Then you can do the assignment as such:
$('#Comments').on('click', '.button', function(e) {
$(this).siblings('.box').toggle();
});
If you have any more questions, just comment!
Side Note .on is for jQuery versions 1.7+. If using older jQuery, use .live or .bind

Targeting an ID that is rendered by a script

I'm using a nifty little script called Tabifier (http://www.barelyfitz.com/projects/tabber/)
Now, long story short, this script, which I run in my head tag, creates a <ul> with <li>s containing <a>s. Also in the head tag it creates IDs for these <a>s. When I inspect the loaded site I can clearly see the ID tags present. However, I cannot call them using getElementById. I've been using
<script>
document.getElementById('rightpanelnav1').style.padding='200px';
</script>
as a sample script in different parts of my code but to no avail. I'm wondering wether it's the placement or order in which these things are defined in my code that's causing it not to recognize the ID. What do you think?
EDIT: I recieved a great answer below, but I still can't get 'rightpanelnav1' to register onclick events...? It's an , there shouldn't be a problem, right? And when I click it, the entire page has been loaded for several seconds...
Firstly, in order to access an element in the DOM, the element must be a part of the DOM (document). So if you place your <script> with getElementById in the page at a place prior to where the element is loaded, it will not see the element in the DOM.
Secondly, it is highly probable that this library you use does its modification on page load, which would mean that no matter where you place your <script> it would have no chance of seeing these elements before running.
As a result, you should have your script wait as well, and do this:
window.onload = function(){
document.getElementById('rightpanelnav1').style.padding='200px';
};
Or for a click event
window.onload = function(){
document.getElementById('rightpanelnav1').onclick = function(){
alert("clicked!");
};
};

innerHtml not working for nested div tags

I am not able to replace .innerHtml for a div tag which is nested in other div tags. I used firebug to make sure that getElementById() is working.
<div class="a">
<div class="b"><div id="hello"></div></div>
</div>
In javascript code I am using:
document.getElementById("hello").innerHTML = "hello world";
Using firebug, I have verified that "hello" div is picked up (that is, it is not null). But the string "hello world" is not showing up.
Kindly help.
Thanks.
use innerHTML rather than innerHtml. note the capitalization.
On a side note, IE also supports innerText.
The example you provided works for me... so, I think you should make sure that the script is executed after the element has been created in the DOM.
For example, place the script element after the div you want to add contents to.
So if this fixes the issue, then you should add an event listener to the window’s onload event which will run all scripts.
And as Amaan said, don’t place a div element inside an a element.

Can I just put my javascript right next to my <div>

If I have some javascript/jQuery acting on a particular div inside tags (for an animation), can I just put the javascript (in a src="link-to-my-js.js" file) right next to my div?
I mean something like the following:
<body>
<div id="special">Some html</div>
<script type="text/javascript">javascript related to my div tag above...</script>
</body>
whereever you add your code wrap it with document .ready.
It will wait till all the dom is ready, so you will be safe.
<script type="text/javascript">
$(document).ready(function() {
});
</script>
You can put them anywhere you want, but
For performance reasons, it's best to put them at the bottom of the page.
DOM manipulation before the page has loaded can cause problems, especially with IE, for example this google maps problem.
You can add the tag anywhere you please. Remember though that if your script tries to act on an element that has not yet been loaded it will fail.
So if your load your script tag before your div and the script isn't activated by an onload event or something similar element will not be found.
On the contrary if the tag appears after the element you can manipulate it as normal.
It does not matter where you put it if you wrap your code with the $(function(){/*code here*/})
reference: http://api.jquery.com/jquery/#jQuery3

Categories

Resources