JavaScript div creation - javascript

Need a small hand here im trying to combine two functions to create a program that takes text from a text area and inserts it into a div (managed that with the first code) the second peace of code im trying to create a div each time, what id like to do is everytime some one writes in the textarea and "posts" the message it will create a new div (rather than the first code which overwrites if anything new is posted).
$(function () {
$('button').click(function () {
var x = $('textarea').val();
$('#test').html(x);
return false;
});
});
second:
function creatediv(id, html, width, height, left, top) {
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
if (width) {
newdiv.style.width = 300;
}
if (height) {
newdiv.style.height = 300;
}
if ((left || top) || (left && top)) {
newdiv.style.position = "absolute";
if (left) {
newdiv.style.left = left;
}
if (top) {
newdiv.style.top = top;
}
}
newdiv.style.background = "#00C";
newdiv.style.border = "4px solid #000";
if (html) {
newdiv.innerHTML = html;
} else {
newdiv.innerHTML = "nothing";
}
document.body.appendChild(newdiv);
}
Being careful tho as I have divs set by css for my master page in asp, dont want to overwrite them. Its important I dont add them to the same div aswell as I will be adding more code later that will contain a button inside the created div to add comments to that div only.
Thanks to any and all that can help!

Yeah, don't bother re-inventing the wheel. Get a library like jQuery and learn it. Faster, easier.
http://jquery.com/
But since jquery is one of your tags, I take it that you are using it?
In that case, just use append:
http://api.jquery.com/append/
$(function () {
$('button').click(function () {
var x = $('textarea').val();
$('#test').append(x);
return false;
});
});

Basically it would be:
$(function () {
$('button').click(function () {
var x = $('textarea').val();
creatediv(..., x, ...);
return false;
});
});
However you'd need to provide the other parameters (id, width, height, left, top) of your function somehow. From your description I can't say what you would want to use there.
BTW, your creatediv has errors. The style properties width, height(and leftand top) require units, so you have to use (for example):
newdiv.style.width = "300px";

See the DEMO
I think that's what u wanted to do.

Related

How to position divs on top ads on Amazon.com

I want to position some divs on top of all ads on Amazon.com like this:
This is for a project of mine. The above picture was achieved through getting the coordinates of the ads using getBoundingClientRect and creating divs, setting top and left based on these coordinates, and appending the divs to document.body. However, since they have absolute position and are children of document.body, they do not move with the ads. For example, if I resize the window, this happens
Also, in product pages, this happens without doing anything.
I have also tried appending the divs to the parents of the iframes/ads, but I can never seem to make them appear outside of their parent. I have tried suggestions from various links, such as making position:absolute, setting bottom or top, making the parents position:relative but nothing has worked. There has been one instance of the div appearing outside of the parent but it was in some random position above it like this.
I seriously don't know how to accomplish this. Ideally, the div would be a sibling of the iframe or something like that, so I don't have to deal with the divs not moving when the window resizes. I just can't seem to get anything work, though.
// Here is the code for appending to parent of iframes.
// The divs just end up overlaying the ad.
function setStyle(element, styleProperties) {
for (var property in styleProperties) {
element.style[property] = styleProperties[property];
}
}
// Regex for getting all the parents of all the iframes
var placements = document.querySelectorAll('div[id^=\'ape_\'][id$=\'placement\']');
for (var i = 0; i < placements.length; ++i) {
var placement = placements[i];
var iframe = placement.getElementsByTagName('iframe')[0];
var debugDiv = document.createElement('div');
debugDiv.id = iframe.id + '_debug_div';
setStyle(debugDiv, {
'backgroundColor': '#ff0000',
'height': '30px',
'display': 'block',
'position': 'absolute',
'top': '-30px',
'zIndex': '16777270',
});
alert(placement.id)
placement.style.position = 'relative'
placement.appendChild(debugDiv);
}
edit:
Here's the getBoundingClientRect code:
function setStyle(element, styleProperties) {
for (var property in styleProperties) {
element.style[property] = styleProperties[property];
}
}
function createDiv(iframeId, top, left, width) {
var div = document.createElement('div');
div.id = iframeId + '_debug_div';
setStyle(div, {
'backgroundColor': '#ccffff',
'backgroundColor': '#ff0000',
'height': '30px',
'width': width.toString() + 'px',
'display': 'block',
'position': 'absolute',
'top': (top - 30).toString() + 'px',
'left': left.toString() + 'px',
'zIndex': '16777270'
});
return div;
}
var placements = document.querySelectorAll('div[id^=\'ape_\'][id$=\'placement\']');
for (var i = 0; i < placements.length; ++i) {
var placement = placements[i];
var iframe = placement.getElementsByTagName('iframe')[0];
var iframeRect = iframe.getBoundingClientRect();
iframeWidth = iframeRect.right - iframeRect.left;
var debugDiv = createDiv(iframe.id, iframeRect.top, iframeRect.left, iframeWidth);
document.body.appendChild(debugDiv);
};
This doesn't work properly when the window is resized. It also does not work properly on product pages for some ads.
Try using the resize eventlistener, with a DOM MutationObserver:
var observeDOM = (function(){
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
return function( obj, callback ){
if( !obj || !obj.nodeType === 1 ) return; // validation
if( MutationObserver ){
// define a new observer
var obs = new MutationObserver(function(mutations, observer){
callback(mutations);
})
// have the observer observe foo for changes in children
obs.observe( obj, { childList:true, subtree:true });
}
else if( window.addEventListener ){
obj.addEventListener('DOMNodeInserted', callback, false);
obj.addEventListener('DOMNodeRemoved', callback, false);
}
}
})();
window.onchange = function(){
observeDOM(document.body, () => {
window.addEventListener('resize', () => {
var placements = document.querySelectorAll('div[id^=\'ape_\'] [id$=\'placement\']');
for (var i = 0; i < placements.length; ++i) {
var placement = placements[i];
var iframe = placement.getElementsByTagName('iframe')[0];
var iframeRect = iframe.getBoundingClientRect();
iframeWidth = iframeRect.right - iframeRect.left;
var debugDiv = createDiv(iframe.id, iframeRect.top, iframeRect.left, iframeWidth);
document.body.appendChild(debugDiv);
}
});
});
}
It's a start. I think the issue with the misplaced bars on the product pages may be fixed by using the onload listener too, although I can't reproduce those issues for whatever reason. If it's not matching some ads altogether, that's likely due to your query selector, but I can't help fix that unfortunately.
The code for the DOM observer is from here - it should detect changes more accurately than onchange, especially for things like flex, where elements can get reordered in the DOM on mobile view. You may also want to wrap this in document.addEventListener("DOMContentLoaded", ... to wait until everything's loaded (at the sacrifice of IE8), or just use jQuery's $(document).ready() (which is compatible with IE8) - however, if you're not already using jQuery, don't import it just for this one function!
Also, you may want to do something about the padding on the body, which may be the cause of the misalignment in some cases. You should probably get it using window.getComputedStyles, and compensate for it. Once again, however, I can't reproduce these errors.
I think, that you want to select the image of the ad.
const adImages = document.querySelectorAll('your ad images');
for (var i = 0; i < adImages.length; ++i) {
adImages[i].parent.insertAdjacentHTML('afterbegin', 'your html');
}
You basicaly set the first child of that parent element on the top.

jQuery 'resize' not working properly

Need some help. I am using jQuery in combination with media queries for some responsive aspects of my header. My client wants the header to be responsive to both devices and manual resize of the window. Therefore, I have set all of my responsive functions in both single functions and then set those same functions wrapped inside of a $(window).on('resize', function). Thanks to another poster on here, I was given the tip to wrap my responsive functions inside of a variable and then pass that variable to the resize function instead of rewriting it all out. This was a great tip and a great thing for me to learn as an intermediate javascript writer. However when I do this, the code does not work within the resize function. If I type it all out exactly the same, it works fine. But if I pass the function it does not work. Can someone please help? Code below:
var win = $(window);
var mainNav = $('.main-nav');
var navItem = $('.main-nav li');
var overlay = $('.nav-overlay');
var header = $('#header');
var subNav = $('.main-nav ul ul');
var overlayIsVisible = false;
var subNavIsVisible = false;
var exitMain = $('.exit-main');
var topNav = $('.top-nav');
var hamburger = $('.tablet-buttons .hamburger');
var exit = $('.tablet-buttons .exit');
if ( header.is('*') ) {
navItem.hover(function() {
overlay.fadeIn('slow');
$(this).find('ul').toggleClass("active");
overlayIsVisible = true;
});
exitMain.click(function() {
overlay.fadeOut('fast');
overlayIsVisible = false;
});
function tabletNav() {
if (win.width() <= 1024) {
topNav.prependTo(overlay);
hamburger.click(function() {
overlay.fadeIn('slow');
hamburger.css('display', 'none');
exit.fadeIn('slow');
});
exit.click(function(){
overlay.fadeOut('slow');
exit.css('display', 'none');
hamburger.fadeIn('slow');
});
}
else{
topNav.insertAfter('.logo');
}
};
/*This makes the above Mobile/Tablet functions also work on resize of window*/
win.on('resize', tabletNav());
};

remove one class when animating

I try to animate menu-panel. It should slide to the left. But it doesn't work right. And I can't understand why.
There are a few issues with the current code (e.g. you were missing a . on one panel selector and not referencing panel1 after changing the panel class. I also switched to absolute positioning with the arrow inside the panel.
I did a little cleanup to make the changes obvious (you should not repeat jQuery selectors - use temp vars instead):
JSFiddle: http://jsfiddle.net/TrueBlueAussie/2x3uT/8/
$(function () {
$('.slider-arrow').click(function () {
var $this = $(this);
var $panel = $(".panel, .panel1");
var left = -53;
var text = '»';
if ($this.hasClass('hide')) {
text = '«';
left = 0;
}
$panel.animate({
left: left
}, 700, function () {
// Animation complete.
$this.html(text).toggleClass('hide').toggleClass('show');
$panel.toggleClass('panel').toggleClass('panel1');
});
});
});
You can tweak the position numbers to make it match what you wanted.

Affect a div when is out of view?

Is there a way to affect a div that is out of view? Ex: when you scroll down the page and the div is no longer visible.
I have an embedded youtube video and I would like to mute it only when the video is no longer in view.
This will mute every video player that is not visible:
$(function() {
var $w = $(window), oldw = 0, oldh = 0, oldt = 0;
function checkVideoVisible() {
if (oldw !== $w.width() || oldh !== $w.height() ||
oldt !== $w.scrollTop()) {
oldw = $w.width();
oldh = $w.height();
oldt = $w.scrollTop();
var top = oldt, bottom = oldt + oldh;
$("video").each(function() {
var $this = $(this);
if ($this.offset().top + $this.height() >= top &&
$this.offset().top < bottom) {
$this.prop("muted", false);
} else {
$this.prop("muted", true);
}
});
}
}
Now to trigger the checking, you can either use a timer:
var timerId = setInterval(checkVideoVisible, 200);
}
Or handle the scroll event:
$w.on("scroll", checkVideoVisible);
}
In the latter case, you will also need to perform a check when any change is made to the dom.
Use this as its probably your best bet im guessing as you;ve posted no code that a pre-written lib will help you
JQ Visible Lib
To implement you need to give your element an id and reference it in script tags or in a js file like this:
$('#element').visible() will return true if visible.
You can then add the part to mute/pause the video based on that state.

How to change the height of div with the content of other div

I have two div in my website page one beside the other(one left and one right),I want to change the height of the left one with the content of the right one using javascript
I tried to have the dynamic height of the right div :
function getHeight() {
var doc = document.getElementById('div.right');
if (document.all) // ok I.E
{
H = doc.currentStyle.height;
}
else // ok FF
{
H = document.defaultView.getComputedStyle(doc, null).height;
}
}​
But I stopped here because I don't know how to pass the javascript variable to my page of style CSS,I mean I dont know how to apply this value in the other div(left div) in the same page automatically.
Any Idea?
Just use
document.getElementById('div.left').style.height = H;
Edit
AFAIK you cant modify an external stylesheet from javascript
Is the height of the div determined at the time the document is served, loaded or or any arbitrary time after the document has loaded?
The code I suggested above was to be used like this(I'm assuming your IE code is correct)
function getHeight() {
var doc = document.getElementById('div.right');
if (document.all) // ok I.E
{
H = doc.currentStyle.height;
}
else // ok FF
{
H = document.defaultView.getComputedStyle(doc, null).height;
}
document.getElementById('div.left').style.height = H;//✔
}
Just to help people I found a great code to change the height of two div autoamtically using a little of Jquery :
<script type='text/javascript'>
$(window).load(function(){
var lh = $('#div.right').height();
var rh = $('#div.left').height();
if (lh >= rh){
//alert('left : ' + lh);
$('#div.left').height(lh);
} else {
//alert('right : ' + rh);
$('#div.right').height(rh);
};
});
</script>
It's works for all navigators.

Categories

Resources