Javascript- creating element as a child of another element - javascript

Hello here's my simple code.I want to display image created in function add(src){} in element main_container.Why doesn't it work?
<head>
</head>
<body>
<style>
#main_container
{
width:1000px;
height:1000px;
position:absolute;
border-style:solid;
}
.jersey
{
width:100px;
height:150px;
position:absolute;
}
</style>
<script>
var dist=-110;
function add(src)
{
dist=dist+110;
var img=document.createElement("img");
img.src=src;
img.style.left=dist+"px";
img.className="jersey";
document.getElementById("main_container").appendChild(img);
}
add("http://www.hdwallpapers.in/walls/abstract_color_background_picture_8016-wide.jpg");
</script>
<div id="main_container"></div>
</body>
</html>

Move the script tag below the element.
Change:
<script>...</script>
<div id="main_container"></div>
To:
<div id="main_container"></div>
<script>...</script>
The browser reads HTML from top to bottom.

beautifulcoder's suggested modification should work, and he is absolutely correct that this is happening because the main_container DOM element will not yet be loaded if it appears after the <script>, but ideally, you should hold off on making DOM manipulations until the document has loaded. You can do this by using the window.onload event:
<script>
function add(src) {
...
}
function initialize() {
add("http://www.hdwallpapers.in/walls/abstract_color_background_picture_8016-wide.jpg");
}
window.onload = initialize;
</script>
<div id="main_container"></div>
or even better, use jQuery's ready event:
function initialize() {
add("http://www.hdwallpapers.in/walls/abstract_color_background_picture_8016-wide.jpg");
}
$(document).ready(initialize);
// $(initialize); <- Shorthand version
Either of these approaches will free you from having to worry about where your script blocks are relative to your page elements.

Related

HTMLObjectElement onclick event doesn't fire [duplicate]

I want to add a click event to an iframe. I used this example and got this:
$(document).ready(function () {
$('#left').bind('click', function(event) { alert('test'); });
});
<iframe src="left.html" id="left">
</iframe>
But unfortunately nothing happens.
When I test it with another element (e.g. a button), it works:
<input type="button" id="left" value="test">
You could attach the click to the iframe content:
$('iframe').load(function(){
$(this).contents().find("body").on('click', function(event) { alert('test'); });
});
Note: this will only work if both pages are in the same domain.
Live demo: http://jsfiddle.net/4HQc4/
Two solutions:
Using :after on a .iframeWrapper element
Using pointer-events:none; one the iframe
1. Using :after
use a transparent overlay ::after pseudo element with higher z-index on the iframe's wrapper DIV element. Such will help the wrapper to register the click:
jQuery(function ($) { // DOM ready
$('.iframeWrapper').on('click', function(e) {
e.preventDefault();
alert('test');
});
});
.iframeWrapper{
display:inline-block;
position:relative;
}
.iframeWrapper::after{ /* I have higher Z-index so I can catch the click! Yey */
content:"";
position:absolute;
z-index:1;
width:100%;
height:100%;
left:0;
top:0;
}
.iframeWrapper iframe{
vertical-align:top;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="iframeWrapper">
<iframe src="http://www.reuters.tv/" frameBorder="0"></iframe>
</div>
2. Using pointer-events:none;
Clicks are not handleable from outside the iframe from an external resource (if the iframe is not in your domain).
You can only create that function inside your 'called into iframe' page, not from within the iframe-hosting page.
How to do it:
You can wrap your iframe into a div
make the click "go through" your iframe using CSS pointer-events:none;
target clicks with jQuery on your wrapping DIV (the iframe parent element)
jQuery(function ($) { // DOM ready
$('.iframeWrapper').on('click', function(e) {
e.preventDefault();
alert('test');
});
});
.iframeWrapper{
display:inline-block;
position:relative;
}
.iframeWrapper iframe{
vertical-align:top;
pointer-events: none; /* let any clicks go trough me */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="iframeWrapper">
<iframe src="http://www.reuters.tv/" frameBorder="0"></iframe>
</div>
NOTA BENE:
No clicks will be registered by the iframe element, so a use-case would be i.e: if by clicking the iframe you want to enlarge it full screen.... Etc...
I got it to work but only after uploading it to a host. I imagine localhost would work fine too.
outer
<html>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function() {
var myFrame = document.getElementById("myFrame");
$(myFrame.contentWindow.document).find("div").on("click", function () { alert("clicked"); });
});
</script>
<body>
<iframe id="myFrame" src="inner.htm"></iframe>
</body>
</html>
inner
<html>
<head>
<style>
div {
padding:2px;
border:1px solid black;
display:inline-block;
}
</style>
</head>
<body>
<div>Click Me</div>
</body>
</html>
Pure Javascript
Not my solution but only this works well.
let myConfObj = {
iframeMouseOver : false
}
window.addEventListener('blur',function(){
if(myConfObj.iframeMouseOver){
console.log('Wow! Iframe Click!');
}
});
document.getElementById('YOUR_CONTAINER_ID').addEventListener('mouseover',function(){
myConfObj.iframeMouseOver = true;
});
document.getElementById('YOUR_CONTAINER_ID').addEventListener('mouseout',function(){
myConfObj.iframeMouseOver = false;
});
$(document).ready(function () {
$('#left').click(function(event) { alert('test'); });
});
<iframe src="left.html" id="left">Your Browser Does Not Support iframes</iframe>
The script would have to be ran entirely from the iframe. I would recommend a different method of calling content, such as php.
iframes aren't really worth the hassle.
The actual problem is that, the click event does not bind to the DOM of the iframe and bind() is deprecated, use .on() to bind the event. Try with the following codes and you will find the borders of the iframe clickable getting that alert.
$('#left').on('click', function(event) { alert('test'); });
Demo of that Issue
So how to get it done?
How you should do is, create a function on iframe page, and call that function from that iframe page.

Page Loader in html page

I am trying to show a loader GIF image in the div section of this html page. But I can't get it to work. The div content is hidden and the GIF image disappears.
CSS:
.loader {
background-image: url(image/Preloader_8.gif);
background-repeat: no-repeat;
height:100px;
width:200px;
}
JavaScript:
<script type="text/javascript">
$(window).load(function() {
$(".loader").fadeOut("slow");
})
</script>
Html:
<body>
<div class="loader">
Loading Image
</div>
</body>
Are you using AJAX to fetch the content in div or simply .load function?
In case of .load() jQuery event,
$( ".loader" ).load( "test.html", function() {
$(".loader").fadeOut("slow");
});
In case of AJAX request, call the function loader in success event of AJAX call.
function loader() {
$(".loader").fadeOut("slow");
});
HTML
<body>
<div class="loader" style="display:none">
Loading Image
</div>
</body>
js
$(window).load(function() {
$(".loader").fadeOut("slow");
})
Please add the following script on the top of your web page
$(".loader").fadeIn();
Add loading div on top of just above script
I think the reason why your code:
$(window).load(function() {
$(".loader").fadeOut("slow");
})
didn't work is because the script is executed after the document is fully loaded.
Following code works.
if (document.readyState == 'complete') {
$(".loader").fadeOut("slow");
} else {
$(window).load(function () {
$(".loader").fadeOut("slow");
})
}
jsfiddle
In your code, the loader class is assigned to the div section, so when you trigger the fade out of the loader page, the entire div assigned to the class fade's out. So better have internal div to which the loader is assigned. This may help check out
<body>
<div class="Image">
<div class="loader">
Loading Image
</div>
</div>
</body>
Working example here
The simplest way of showing loader.gif on web page as:
<div id="divloader" class="ShowLoader">
<img id="imgUpdateProgress" class="loaderIMG" src="../../images/newloader.gif" alt="Loading ..." title="Loading ..." />
</div>
CSS code
<style>
.loaderIMG {
padding: 10px;
position: fixed;
top: 45%;
left: 45%;
width: 80px;
}
.HideLoader {
display: none;
}
</style>
jQuery code:
$(document).ready(function () {
$("#divloader").addClass("HideLoader");
});
First check that your jQuery library working or not by showing alert msg, and then check that image path from browser inspect element.
Add this code:
$(document).ready(function(){
$(".loader").fadeOut("slow");
})
jsfiddle

Javascript change width of image onclick

I'm a complete noob when it comes to javascript. Would there be anyway to change an image after it is clicked, some way to trigger a js function to change the css. It would have to be triggered by an event and something other than onclick, onfocus probably.
<style>
#pic {
width:100px;
height:100px;
}
</style>
</head>
<body>
<img src='nope.jpg' id='pic' onclick="mouseOver()"></img>
<script type='text/javascript'>
function mouseOver() {
document.getElementById('pic').style.width="400px";
document.getElementById('pic').style.height="400px";
}
</script>
try this...
function mouseOver() {
document.getElementById('image').style.height = "400px";
}
First i edited the question , because the function was not defined correctly .
Second :
to access the height property of any element , you should use style.height , and should add "px" to the value.
please spend more time searching for answers , instead of posting a new question.
Change the JS to this:
var image = document.getElementById('image');
function mouseOver() {
image.style.height="600px";
}
image.onclick = mouseOver;
Setting values you can use directly style attribute, but remember that asking for them is a greater problem:
Please refer to this one:
Get a CSS value with JavaScript
This should work
<style>
#pic {
width:100px;
height:100px;
}
</style>
</head>
<body>
<img
width="100"
onmouseOver="this.width=400; this.height=400"
onclick="this.width=100"
alt="RESIZE IMAGE"
id='pic'
src='nope.jpg'
/>
just copy and edit the image tag code as needed

Cloning div and changing attributes

I performed various research but I din't find a solution for my problem. I created a drop down select with css to change color of background, but then when I try to clone it with Javascript, the new copy doesn't change attributes in selection so it keep the original color. Just try it, add some copy and try to change the colors.
I'm new here, i'm not very able to add code so here's to try:
http://jsfiddle.net/gabry501/FUyA3/
or github
https://github.com/gabry501/Test-Color/blob/master/test.html
HEAD
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function cloning() {
var container = document.getElementById('fine');
var clone = document.getElementById('contenitore').cloneNode(true);
container.appendChild (clone);
}
STYLE
select option,
select {
background-color:white;
width:200px;
height:200px;
}
select option[value="1"],
select.o1
{
background-color:blue;
}
select option[value="2"],
select.o2
{
background-color:red;
}
select option[value="3"],
select.o3
{
background-color:orange;
}
BODY
<div style="width:1100px;
height:250px;" id="contenitore">
SCRIPT
<script>$('select[id$=-status][id^=id_item-]').children().each(
function (){
if($(this).val() == 0){
$(this).css('backgroundColor','white');
}
if($(this).val() == 1){
$(this).css('backgroundColor','green');
}
if($(this).val() == 2){
$(this).css('backgroundColor','red');
}
if($(this).val() == 3){
$(this).css('backgroundColor','orange');
}
}
);</script>
<script>
$('select[id$=-status][id^=id_item-]').change(function (){
var color = $(this).find('option:selected').val();
$(this).removeClass('o1 o2 o3').addClass('o' + $(this).find('option:selected').val());
}).change();
It seems you are depending on a listener to modify the style. Listeners added using addEventListener are not included in a cloned element, you have to attach them seperately.
Note that listeners added inline, or using attachEvent are cloned.
cloneNode() copies only the data of the element in question. it does not copy over the event listeners. You need to do that manually..
Use the jQuery clone() method..
function cloning() {
var container = document.getElementById('fine');
var clone = $(document.getElementById('contenitore')).clone(true);
$(container).append(clone);
}
Check Fiddle
PS : Also you code looks really messy . You can scale it down..
UPDATE
I have made a few changes to the code .
1.) Removed the click event from HTML and added that to the script.
2.) Removed the ID's and replaced by a className as ID's in a document are supposed to
be Unique.
3.) Removed extra styles and replaced with a simple class Name.
4.) Better to have separate files for style and script than including it in HTML.
5.) If you want it to work , move the styles and the script to the corresponding tags I
have marked..
HTML
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<meta charset="UTF-8">
<title>Untitled Document</title>
<style type="text/css">
// Add the Styles here
</style>
</head>
<body>
<div style="width:1100px; height:250px;" class="contenitore">
<select name="item-0-status">
<option value="" disabled="disabled" class="optionGroup">SELECT
COLOR</option>
<option value="1"> BLUE</option>
<option value="2"> RED </option>
<option value="3"> ORANGE</option>
</select>
</div> <!--Contenitore -->
<div id="fine"></div>
<br>
<div id="bottone">
<input id="btn" type="button" Value="ADD">
</div>
<script type="text/javascript">
// Script Comes Here
</script>
</body>
</html>
Javascript
$(function() {
$('select[name="item-0-status"]').change(function() {
$(this).removeClass('o1 o2 o3').addClass('o' + $(this).val());
}).change();
$('#btn').on('click', function() {
var container = document.getElementById('fine');
var clone = $(document.getElementsByClassName('contenitore')[0]).clone(true);
$(container).append(clone);
});
});​
Styles
#bottone
{
float:left;
text-align:left;
clear:left;
margin-top:20px;
}
select option,select
{
background-color:#FFF;
width:200px;
height:200px;
}
.o1
{
background-color:blue;
}
.o2
{
background-color:red;
}
.o3
{
background-color:orange;
}​
UPDATED FIDDLE
You have to use $('.el').live('change', fn) instead of $('.el').change(fn) because you're adding an element after the DOM is loaded.
See this jsfiddle: http://jsfiddle.net/FUyA3/1/
try deep cloning - i.e $(selector).clone(true)....then events will also be cloned

Fade in divs one after another

Hey there guys, Im good with HTML and CSS but have only jsut started to scratch the surface of jQuery. I'm looking to make 3 divs fade in on page load one after another.
So far I have this
<script type="text/javascript">
$('#1').hide().fadeIn(1500);
$('#2').hide().fadeIn(1500);
$('#3').hide().fadeIn(1500);
</script>
I heard that to use css to set the display to none is a nightmare for anyone with a non JavaScript browser so I used the hide function to initially hide the divs.
But this only fades them in all at once.
Any ideas?
You can .delay() each so the one before fades in at the right time, for example:
$("#1, #2, #3").hide().each(function(i) {
$(this).delay(i*1500).fadeIn(1500);
});
This fades them in...in the same order they occur in the page which is usually what you're after, the first is delayed 0 so it's instant, the second is delayed 1500ms (so when the first finishes, etc). In the .each() callback i is the index, starting with 0 so you can use that to quickly calculate the right delay here.
Another advantage here is this approach is much easier to maintain, give them a class for example then you can just do:
$(".fadeMe").hide().each(function(i) {
$(this).delay(i*1500).fadeIn(1500);
});
Then you require zero maintenance on the JavaScript side to add additional <div> elements to fade.
The fade in command contains a call back function, see documentation. This means you could chain the events.
<script type="text/javascript">
$('#1, #2, #3').hide();
$('#1').fadeIn(1500, function(){ $('#2').fadeIn(1500, function(){$('#2').fadeIn(1500)})});
</script>
<script type="text/javascript">
$('#1').hide().fadeIn(1500, function(){
$('#2').hide().fadeIn(1500, function(){
$('#3').hide().fadeIn(1500);
});
});
</script>
Using the Delay function as following:
<script type="text/javascript">
$('#1').hide().fadeIn(1500);
$('#2').hide().delay(1500).fadeIn(1500);
$('#3').hide().delay(3000).fadeIn(1500);
</script>
Here is a cleaner and generic way to achieve this effect:
check it out on http://jsfiddle.net/BztLx/20/
Logic trick relies on the callback functionality of the fadeIn and using .eq() as an iterator over the selected elements.
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function sequentialFadeIn(selectorText, speed, display, callBack) {
display = typeof display !== 'undefined' ? display : "block";
var els = $(selectorText), i = 0;
(function helper() {
els.eq(i++).fadeIn(speed, helper).css("display", display);
if (callback && i === els.length) callback();
})();
}
sequentialFadeIn(".toBeFaddedIn", "slow", "inline-block", function() {
console.log("I am just an optional callback");
});​
});
</script>
</head>
<body><style media="screen" type="text/css">
.hello {
background-color: blue;
height:50px;
width: 50px;
display: none;
}
</style>
<div class="hello toBeFaddedIn"></div>
<div class="hello toBeFaddedIn"></div>
<div class="hello toBeFaddedIn"></div>
<div class="hello toBeFaddedIn"></div>
<div class="hello toBeFaddedIn"></div>
</body></html>

Categories