Styling elements created dynamically - javascript

i am a newbee so sorry if my question is basic.
i have written a code (with the help of the forum offcourse) where by clicking on an image another one appears and when you click on the new one, again another one appears and so on.
the problem is i can not add an style to the code and make the images appear in different positions to make a layout.
can anyone here help me?
thank you so much
<meta charset="utf-8">
<title> COOPER BLACK </title>
<link rel="stylesheet" type="text/javascript" href="style.css" media="screen">
</head>
<div class="container">
<script type="text/javaSCRIPT">
var i = 1
function imageClick() {
if (! this.alreadyClicked)
{
addimage();
counter();
this.alreadyClicked = true;
}
}
function addimage() {
var img = document.createElement("img");
img.src = "images/d"+i+".jpg";
img.onclick = imageClick;
document.body.appendChild(img);
}
function counter() {
i = i + 1
}
</script>
<div class="first">
<input class="first" type="image" src="images/d0.jpg" onclick="imageClick();">
</div>
</div>

Try setting the class attribute this way
img.setAttribute("class", "YourClassName");
Then apply the style to YourClassName in a CSS file/style tag. (Might also want to call the script after you load the CSS) Like so
.YourClassName { /* style here */ }
Edit:
You can also check if the elements are rendered well (the HTML tags have the class names and onClick methods) using the console (press F12 on the page)

Related

images are not rendering on website?

ive looked at other answers and none of them seemed to work which is why i decided to re-ask the question and show you guy my code so you can help me so here it is :
function searchForm() {
var body = document.getElementsByTagName('body')[0]
var search = document.getElementById('GIF-search').value;
var content = document.getElementById('content')
var xhr = $.get("http://api.giphy.com/v1/gifs/search?q=" + search + "&api_key=api");
xhr.done(function(data) {
var image = data;
var GIF = image['data'][0]['embed_url'];
var GIF_image = document.createElement('img');
GIF_image.setAttribute('src', GIF);
GIF_image.setAttribue('id', 'GIF');
content.appendChild(GIF_image)
});
}
var searchGIF = document.getElementById('search_GIF')
searchGIF.addEventListener('click', searchForm, false);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>GIF viewer</title>
<style type="text/css">
#content {
width: 100%
}
img {
width: 250px;
height: 250px
}
</style>
</head>
<body>
<div id="Search">
<input type="text" name="" id="GIF-search">
<button id="search_GIF">Search GIFs</button>
</div>
<div id="content"></div>
<script src="jquery-3.2.1.js"></script>
<script src="GIFsearch.js"></script>
</body>
</html>
my problem here is that im getting a blank image on my site can anyone explain why this is happening and how i can fix it so it will actually show the GIF?
btw i know in the $.get("http://api.giphy.com/v1/gifs/search?q=" + search + "&api_key=api"); the apikey in not valid (this is on purpose);
Couple of things:
There was no jQuery in jsfiddle. Make sure you have it in your code.
Make https:// api call if your page is using https:// protocol.
setAttribute when you are setting id has got a typo. Look carefully.
URL you are getting at image['data'][0]['embed_url'] is not a image url but a webpage url. Try console log it and see. So you cant really set it as a src of some img tag. Find the correct image url and then proceed.

Page load Overlay

I have a site that I would like for new users to see a contact us when the page loads. I have tried numerous methods and gotten an overlay but the ability to hide and continue onto the page is not working.
$(document).ready(function() {
$('#overlay').fadeIn();
});
$('button').click(function() {
$('#overlay').fadeOut(200, "linear");
});
function openNav() {
document.getElementById("myNav").style.height = "100%";
}
function closeNav() {
document.getElementById("myNav").style.height = "0%";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div id="myNav" class="overlay">
<h1>Text</h1>
<button>hide</button>
</div>
</body>
</html>
If any suggestions for closing the popup exist please share.
There are a bunch of ways to hide an element, being the most common one to set
document.getElementById("myNav").style.display = "none";
And to show it again
// Empty to have the one specified by CSS or the element default.
// Or "block", "inline", "inline-block"... Whatever fits you better.
document.getElementById("myNav").style.display = "";
If you hide by height (is a good decision if you have a CSS transision, but you need fixed heights), you need to set the element overflow to hidden. By default, if the content of an element is bigger than the element size it will be shown, so your .overlay class should have overflow: hidden to hide it.
By the way, you are using dynamic heights so you are not using transitions. As a recommendation, use the display way instead.
EDIT: Just noticed the ID problem that #Rubenxfd points out. He is right. Is going to be the main problem for sure.
Also, another problem you have is that you run this code
$('button').click(function() {
$('#overlay').fadeOut(200, "linear");
});
before the button element is rendered, so the event won't attach to it as it don't exists. You should attach it when the page is ready, so you have to move it inside the ready function, like this:
$(document).ready(function() {
$('#myNav').fadeIn();
$('button').click(function() {
$('#myNav').fadeOut(200, "linear");
});
});
Notice the difference.
You are using an class, but calling an id in your jQuery.
Change your jQuery to this:
$(document).ready(function() {
$('.overlay').fadeIn();
});
$('button').click(function() {
$('.overlay').fadeOut(200, "linear");
});
Fiddle
You had a # instead of a ..
$('#overlay').fadeOut(200, "linear"); will happen to the element with the id overlay not to the class. if you write $('.overlay').fadeOut(200, "linear");it will happen to all elements with the class of overlay
$(document).ready(function() {
$('.overlay').fadeIn();
});
$('button').click(function() {
$('.overlay').fadeOut(200, "linear");
});
function openNav() {
document.getElementById("myNav").style.height = "100%";
}
function closeNav() {
document.getElementById("myNav").style.height = "0%";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div id="myNav" class="overlay">
<h1>Text</h1>
<button>hide</button>
</div>
</body>
</html>

Position of script tag in html

I am trying to duplicate Expanding Text Areas Made Elegant
Basically it explains how we can achieve something like fb comment box, where its size increases as text files the textarea.
I have this in my index.html:
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
<script src="test.js"></script>
</head>
<body>
<figure>
<div class="expandingArea">
<pre><span></span><br></pre>
<textarea></textarea>
</div>
</figure>
</body>
</html>
And my test.js looks like:
This doesn't really works.
However if I move everything inside the js file to a script tag inside body then it works fine. So my index file would look like:
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
</head>
<body>
<figure>
<div class="expandingArea">
<pre><span></span><br></pre>
<textarea></textarea>
</div>
</figure>
<script>
function makeExpandingArea(container) {
var area = container.querySelector('textarea');
var span = container.querySelector('span');
if (area.addEventListener) {
area.addEventListener('input', function() {
span.textContent = area.value;
}, false);
span.textContent = area.value;
} else if (area.attachEvent) {
// IE8 compatibility
area.attachEvent('onpropertychange', function() {
span.innerText = area.value;
});
span.innerText = area.value;
}
// Enable extra CSS
container.className += ' active';
}var areas = document.querySelectorAll('.expandingArea');
var l = areas.length;while (l--) {
makeExpandingArea(areas[l]);
}
</script>
</body>
</html>
You're not actually using onload
Your formatting is so messed up it's hard to tell, but your init code is in a while loop at the bottom after your onload function.
When you include it in the <head> it runs before any elements exist. That's why the position of it matters.
In your browser(I recommend Chrome for testing) open up the developer tools(via right click and selecting inspect element) and make sure your test.js file's path is correct. Do this by selecting the 'Sources' tab on the top of the developer tools window and then selecting the test.js file on the list of sources.
I also consider it best practice to load your js files at the bottom of your web documents(before the last body tag) to guarantee they load AFTER your dom elements load.
try this in your code:
I have used inside a table andapply a css class "form-control". The properties of this text areas are in side tag in side
html code:
<html>
<body>
<table>
<tr>
<td>Description:</td>
<td><textarea name="DESCRIPTION" id="DESCRIPTION" class="form-control"></textarea></td>
<td></td>
</tr>
</table>
//css-code required inside html:
<style>
textarea.form-control {
height: auto;
resize: none;
width: 300px;
}
</style>
</body>
</html>

Copy CSS style from one element to a new element in a separate document

How do I copy CSS style from one element to a new element in a separate document (an IFRAME for instance)?
I've tried to do so by using bobince's answer at JavaScript & copy style.
Please see my attempt below.
Thank you
http://jsbin.com/uvOFIXIZ/1/
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>copy CSS</title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<style type='text/css'>
.myClass p {font-size:20px;color:blue;}
</style>
<script type="text/javascript">
$(function () {
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
$(iframe).load(function(){
$('.myClass').each(function(){
var to=iframe.contentWindow.document.body.appendChild(this.cloneNode(true));
console.log(to);
var from=this;
//Option 1
to.style.cssText= from.style.cssText;
//Option 2
for (var i= from.style.length; i-->0;) {
var name= from.style[i];
to.style.setProperty(name,
from.style.getPropertyValue(name),
priority= from.style.getPropertyPriority(name)
);
}
});
});
});
</script>
</head>
<body>
<div class="myClass">
<p>Stuff!</p>
<img alt="an image" src="dropdown_arrow_blue.gif">
</div>
<div class="myClass">
<p>More stuff!</p>
</div>
</body>
</html>
EDIT. Technically, this should work, however, it seems overkill.
//Option 3
var arrStyleSheets = document.getElementsByTagName("link");
for (var i = 0; i < arrStyleSheets.length; i++){
iframe.contentWindow.document.head.appendChild(arrStyleSheets[i].cloneNode(true));
}
var arrStyle = document.getElementsByTagName("style");
for (var i = 0; i < arrStyle.length; i++){
iframe.contentWindow.document.head.appendChild(arrStyle[i].cloneNode(true));
}
You could try what this post refers to -- since you're able to control the src document the iframe uses you can have css class defined in parent then use it in the iframe. link to another post on the subject.
You could attach the stylesheet of the previous document that you want to transfer the css from to your web page and import only what you want using plain css. I usually keep a class file with general properties and setting for various element such as fonts.

Adding style to Header when div is clicked using Javascript

My intent is to add a class to the header when a div is clicked. I have included the website I'm working with, just to make thing's easier:
URL - http://itsmontoya.com/work/iM/
I have added a class 'expanded' to the header. This is to show how the navigation should look after the button has been pressed. I created a simple Javascript which is supposed to provide an alert when I click the button. I can't seem to get this to work. Any ideas of what I did wrong?
Thanks!
EDIT - I was able to get the alert to properly work when clicking the button div. I'm very close to having this complete! :) Now I'm getting stuck with the variable not passing correctly.
<script type= "text/javascript">
var expanded = false;
function btnClick(){
alert('The variable expanded is '+expanded);
if(expanded === false) {
document.getElementById("header").className = "expanded";
var expanded = true;
} else {
document.getElementById("header").className.replace(/\bexpanded\b/,'');
var expanded = false;
}
};
</script>
I'm updating the ftp server now :)
When using jQuery, you have to bind your events in such a way that the elements have already loaded.
You have:
<script type= "text/javascript">
$("#expandBtn").click(function(){
alert('hello');
});
</script>
I think what you want is:
<script type= "text/javascript">
$(document).ready(function(){
$("#expandBtn").click(function(){
alert('hello');
$('header').addClass('expanded');
});
});
</script>
The API documentation is going to be your friend here. First step -- ready().
UPDATE
You have this call to jQuery:
$j('#header').addClass('expanded');
But your markup is for the HTML5 element <header>. In that case your jQuery needs to change to:
$j('header').addClass('expanded');
Where $j is your jQuery object. More typically you would use $ or jQuery.
Time to bone up on jQuery Selectors!
UPDATE
Here's your updated page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>itsMontoya</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="shortcut icon" href="/favicon.ico" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script type= "text/javascript">
$(document).ready(function(){
$('.expandBtn').bind('click', function(){
$('header').toggleClass('expanded');
});
});
</script>
</head>
<body>
<div class="wrap">
<header id="header" class="">
<div class="blackBG transparent"></div>
<nav>
<ul>
<li>
Home<img src="images/home.png">
</li>
<li>
Pictures<img src="images/pictures.png">
</li>
<li>
Music<img src="images/mymusic.png">
</li>
<li>
About Me<img src="images/aboutme.png">
</li>
<li>
Resume<img src="images/resume.png">
</li>
</ul>
</nav>
<div id="logo" class="logo"><p>itsMontoya</p></div><div id="expandBtn" class="expandBtn anchor"></div>
</header>
<section class="content">
<article class="blogEntry"></article>
</section>
<footer class="anchor">
<div class="over anchor"><p>2011 itsMontoya.com</p></div>
<div class="blackBG transparent anchor under"></div>
</footer>
</div>
</body>
</html>
Using jQuery:
$('#your_div_id').click(function(){
console.log("Clicked.");
$("#header").addClass('expanded');
});
Update
In your code:
var expanded = false;
function btnClick(test){
if($expanded === false) {
.
.
.
What the heck is $expanded? Notice that in JavaScript we don't need the $ sign for variables.
This is how you would bind a click handler to your div and add the class to your header:
var yourDiv = document.getElementById('your-div-id');
var header = document.getElementById('header');
yourDiv.onclick = function(){
alert("yourDiv was clicked");
header.className = "newCssClass";
};
The above assumes markup like so:
<div id="your-div-id">Click</div>
<div id="header"></div>
Here's an example.
Update: The reason that the expanded variable isn't working as you'd expect is because you're creating a duplicate local variable called expanded in your btnClick() method. As a result, the global expanded variable you declare outside the function is never updated.
This is being caused by how you're using the var keyword:
When used outside a function, var creates a global variable that's accessible anywhere within the current document.
When used inside a function var creates a local variable that is accessible only within that function.
Here's your function cleaned up to work as you'd expect:
// Define global variable (using var outside function)
var expanded = true;
function btnClick(){
alert('The variable expanded is '+expanded);
// Condition for true
if(expanded) {
// do something
// Condition for false
} else {
// do something else
}
// Flips boolean value of the global variable (notice lack of var keyword)
expanded = !expanded;
}
Here's an example showing the correct way to update the expanded variable.

Categories