I want #result to being scaled to #sidebar height if set. If not, leaving #result at its original height.
My code:
window.onload = setDiv;
function setDiv() {
var e = document.getElementById('sidebar'); // Get the sidebar infos
var eh = e.offsetHeight // div height
if ( typeof(eh) == "undefined" || typeof(eh) == null) { // if sidebar isnt in the page
alert(eh);
return true;
} else {
var eh = e.offsetHeight // div height
var d = document.getElementById('result') // Get the result div height
var dh = d.offsetHeight // div height
d.style.height = eh + 65 + 'px'; // Set result div height to sidebar height
alert(d);
document.write(dh);
return false;
}
}
I don't think HTML/CSS is needed.
Thank you.
This line seems wrong:
if ( typeof(eh) == "undefined" || "null") { // if sidebar isnt in the page
try this:
if ( typeof(eh) == "undefined" || typeof(eh) == null) { // if sidebar isnt in the page
Also, I would add in a try catch block. If there is a throw you won't even know your code did not execute.
This causes an error because e does not exist (yet):
var e = document.getElementById('sidebar'); // <<< This is what doesn't work
This is because your window.onload is not done right. Take the parentheses off:
window.onload = setDiv;
http://jsfiddle.net/userdude/u8DZx/3/
I want to demonstrate how easy this is to do in a library like jQuery. window.onload does not always work the way you think either; it's often better to use onDomReady, or $(document).ready() in jQuery. You can also add multiple handlers at different points in the page load, which is more difficult just using the window.onload method.
$(document).ready(function(){
setTimeout(function(){setDiv();},2000); // So you can see the transition
});
function setDiv() {
var $sidebar = $('#sidebar');
if ($sidebar.size() === 0) {
return true;
} else {
$('#result').animate({
height : $('#sidebar').height()
}, 5000);
return false;
}
}
http://jsfiddle.net/userdude/u8DZx/1/
If you don't want the effect, just do:
$('#result').height($('#sidebar').height());
And if you actually meant to use offsetHeight, which it doesn't sound like that's what you want (height instead), you could do this:
$(document).ready(function(){
setTimeout(function(){setDiv();},2000); // So you can see the transition
});
function setDiv() {
var $sidebar = $('#sidebar');
if ($sidebar.size() === 0) {
return true;
} else {
$('#result').offset($('#sidebar').offset());
return false;
}
}
http://jsfiddle.net/userdude/u8DZx/2/
Related
I have written this scrip to take out ads on a website. Was working on it the whole day.
This is the JS code:
var timer = setInterval(deletor, 1);
function deletor() {
timer;
var slider = document.querySelector("#slider-con");
var bannerTop = document.querySelector("#MainContent > div:nth-child(2)")
var bannerMiddle = document.querySelector("#MainContent > iframe");
var bannerRandom = document.querySelector("#MainContent > div:nth-child(7)");
var bannerRandom2 = document.querySelector("#MainContent > div:nth-child(6)");
if (slider == undefined) {
return false;
} else {
slider.parentNode.removeChild(slider);
};
if (bannerTop == undefined) {
return false;
} else {
bannerTop.parentNode.removeChild(bannerTop);
};
if (bannerMiddle == undefined) {
return false;
} else {
bannerMiddle.parentNode.removeChild(bannerMiddle);
};
if (bannerRandom == undefined) {
return false;
} else {
bannerRandom.parentNode.removeChild(bannerRandom);
};
if (bannerRandom2 == undefined) {
return false;
} else {
bannerRandom2.parentNode.removeChild(bannerRandom2);
};
};
Now, as you can see, it gets the values first and then goes through if statements. Idea behind this is: On first try, it deletes the elements and on the second one, it stops the function.
But when I inserted this last element, it won't delete it. The ID is correct, everything is correct but it won't delete the element, so I keep getting the same alert over and over.
Also, I found out that, I get this banner ad on two places. When I have "var bannerRandom = document.querySelector("#MainContent > div:nth-child(7)");" this, it appears as "document.querySelector("#MainContent > div:nth-child(6)")" this, and when I have both, it appears as "document.querySelector("#MainContent > div:nth-child(6)")" this. And it's not deleted.
Console shows no errors.
Your various statements in the form:
if (slider == undefined) {
return false;
} else {
slider.parentNode.removeChild(slider);
};
mean this: "If slider wasn't found in the DOM, exit the function. Otherwise, remove the slider and continue the function."
So that means your function will terminate the first time one of the elements you're looking for doesn't exist. Since it terminates then, none of the other elements after it is checked. That seems unlikely to be what you want to do.
You probably just wanted:
if (slider) {
slider.parentNode.removeChild(slider);
}
...and so on.
Note that you don't put ; at the end of a block attached to a flow-control statement like if or else, which is why I've removed it above. (Doing so is harmless, because JavaScript ignores them; but it's pointless.)
I'm trying to apply a series of classes to a nav that cause it to shrink if the window is either resized or scrolled passed a certain point. However, I believe my conditions are cancelling each other out, and I'm not sure how to structure the if-statements or if it is better to just pass a variable.
Here's what I am trying to accomplish:
If the window is resized between a certain set of media queries, shrink the nav
If the window is outside of those break-points, and the user scrolls passed 1 (I used one just for example purposes in my code so I could see it right away) the nav will shrink and if they scroll up again, it will become it's full size
My code is here:
$(document).ready(function() {
var logo = $('.logo');
var topLevelListItems = $('.mainNav li');
var navShrink = false;
var mQ = window.matchMedia( '(min-width: 100px) and (max-width: 770px)' );
$(window).resize(function() {
if ( mQ.matches ) {
$('nav').addClass('shrink');
$('.nav-fixedWidth').addClass('shrink');
logo.addClass('shrink');
topLevelListItems.addClass('shrink');
navShrink = true;
}
else{
$('nav').removeClass('shrink');
$('.nav-fixedWidth').removeClass('shrink');
logo.removeClass('shrink');
topLevelListItems.removeClass('shrink');
navShrink = false;
}
});//end of resize function
$(window).onscroll(function(){
if( !(mQ.match) && $(this).scrollTop >= 1 ) {
$('nav').addClass('shrink');
$('.nav-fixedWidth').addClass('shrink');
logo.addClass('shrink');
topLevelListItems.addClass('shrink');
navShrink = true;
} else {
$('nav').removeClass('shrink');
$('.nav-fixedWidth').removeClass('shrink');
logo.removeClass('shrink');
topLevelListItems.removeClass('shrink');
navShrink = false;
}
});//end of scroll function
});//end of doc
Could it simply be a typo in your onscroll function?
i.e you have:
if( !(mQ.match) && $(this).scrollTop >= 1 ) { ...
should it not be:
if( !(mQ.matches) && $(this).scrollTop >= 1 ) { ...
How to be sure if parent element has css position property setted up ?
if(!$('#element').parent().css('position')){
//here I need to be sure to avoid no rewrite the old position if position is already setted up
//absolute fixed etc....
$('#element').parent().css('position','relative')
}
Some like this work on cross browsers ?
Please follow the below method :
function elementOrParentIsFixed(element) {
var $element = $(element);
var $checkElements = $element.add($element.parents());
var isFixed = false;
$checkElements.each(function(){
if ($(this).css("position") === "relative") {
isFixed = true;
return false;
}
});
return
}
So based on #Danish suggestion (copy-pasted from : Detect whether an element has position:fixed (possibly by parent element) via jQuery )
I write this:
function parentHasPosition(element){
var parent = element.parent();
if(
parent.css('position') === 'static' ||
parent.css('position') === 'absolute' ||
parent.css('position') === 'fixed' ||
parent.css('position') === 'sticky'
){
return true;
}
return false;
}
I have a function in JS that hides the element parsed:
function hide(id){
document.getElementById(id).style.display = "none";
}
How can I create a function that brings back the element to the default style value. For instance a div display property is "block" as for an image is "inline-block", other elements are "inline" or lists are "list-item" How can I bring them back their default state?
function show(id){
document.getElementById(id).style.display = "?????";
}
I know how to do it in Jquery but it is not an option.
In CSS there might be styles for the elements including style:none, which need to be overwritten to the default value.
Since there is CSS in my example making style.display = '' eliminates the style added with JS but gets back to whatever style is added in CSS, I want to bring it back to its default value even before assigning styles with CSS.
I tried this as it was suggested in a link in one of the comments:
elem = document.getElementById(id);
var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("display");
but in this case 'theCSSprop' returns "none" for a div, when I expect "block"
Any ideas?
Thanks.
You need just assign it to empty value:
document.getElementById(id).style.display = "";
Or using removeProperty method:
document.getElementById(id).style.removeProperty( 'display' );
But note that removeProperty will not work on IE<9.
If you want to get original CSS value you will need probably to get it from empty <iframe> element. I created example on jsFiddle how to get current value using getComputedStyle and iframe value on jsFiddle.
Please note that getComputedStyle not support old versions of IE. It support IE9+.
For IE8 you should use Element.currentStyle
Note:
If you define display:none; for a class or tag (either in a separate css file or in the head section), the above methods won't work.
Then you will have to determine which type of tag + class it is and manually assign the value specific to it.
These are examples of what may not work:
// In many cases this won't work:
function ShowHide_WillRarelyWork(id, bDisplay) {
// Note: This will fail if parent is of other tag than element.
var o = document.getElementById(id);
if (o == null) return;
//
if (bDisplay) {
o.style.display = 'inherit';
o.style.visibility = true;
}
else {
o.style.display = 'none';
}
} // ShowHide_WillRarelyWork(...)
// This will work in most, but not all, cases:
function ShowHide_MayWork(id, bDisplay) {
// Note: This will fail if element is declared as 'none' in css.
var o = document.getElementById(id);
if (o == null) return;
//
if (bDisplay) {
o.style.display = null;
o.style.visibility = true;
}
else {
o.style.display = 'none';
}
} // ShowHide_MayWork(...)
This is long but will most probably work:
function getDefaultDisplayByTag(sTag) {
// This is not fully implemented, as that would be very long...
// See http://www.w3.org/TR/CSS21/sample.html for full list.
switch (sTag) {
case 'div':
case 'ul':
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6': return 'block';
//
case 'li': return 'list-item';
//
case 'table': return 'table';
//
case 'td':
case 'th': return 'table-cell';
}
// Fallback:
return 'block';
} // getDefaultDisplayByTag(...)
//
function computeDisplay(o) {
var oFunction = window.getComputedStyle;
if (oFunction) {
var oStyle = window.getComputedStyle(o)
if ((oStyle) && (oStyle.getPropertyValue)) {
return oStyle.getPropertyValue('display');
}
}
if (window.currentStyle) {
return window.currentStyle.display;
}
return null; // <-- This is going to be a bad day...
} // computeStyle(...)
//
// This will most probably work:
function ShowHideObject_WillProbablyWork(o, bDisplay, bMaybeRecursive) {
if ((o == null) || (o == undefined) || (o == document) || (o.tagName == undefined)) return;
//
if (bDisplay == null) bDisplay = true
if (!bDisplay) {
o.style.display = 'none';
}
else {
// First remove any directly set display:none;
if ((o.style.display == 'none') || (o.style.display == '')) {
o.style.display = null;
}
//
var sDisplay = null;
var sDisplayCurrent = computeDisplay(o);
var oParent = o.parentNode;
// Was this element hidden via css?
if ((sDisplayCurrent == null) || (sDisplayCurrent == 'none')) {
// We must determing a sensible display value:
var sTag = o.tagName;
sDisplay = getDefaultDisplayByTag(sTag);
} // else: if ((sDisplayCurrent != null) && (sDisplayCurrent != 'none'))
//
// Make sure visibility is also on:
if (sDisplay != null) o.style.display = sDisplay;
o.style.visibility = true;
//
if (bMaybeRecursive) {
// We should travel up the tree and make sure parent are also displayed:
ShowHideObject_WillProbablyWork(oParent, true, true);
}
} // else: if (!bDisplay) ...
//
} // ShowHideObject_WillProbablyWork(...)
//
// ... and finally:
function ShowHideId_WillProbablyWork(id, bDisplay, bMaybeRecursive)
var o = document.getElementById(id);
ShowHideObject_WillProbablyWork(o, bDisplay, bMaybeRecursive)
} // ShowHideId_WillProbablyWork(...)
Of course this could be shortened a bit; but that's how it looks in my source.
Here is one more solution for retrieving any property default value of any element. Idea is following:
Get nodeName of specific element
Append a fake element of the same node name to body
Get any property value of the fake element.
Remove fake element.
function getDefaultValue(element, property) {
var elDefault = document.createElement(element.nodeName);
document.body.appendChild(elDefault);
propertyValue = window.getComputedStyle(elDefault,null).getPropertyValue(property);
document.body.removeChild(elDefault);
return propertyValue;
}
function resetPropertyValue (element,propertyName) {
var propertyDefaultValue = getDefaultValue(element, propertyName);
if (element.style.setProperty) {
element.style.setProperty (propertyName, propertyDefaultValue, null);
}
else {
element.style.setAttribute (propertyName, propertyDefaultValue);
}
}
#d {
background: teal;
display: inline;
}
<button onclick="resetPropertyValue(document.getElementById('d'), 'display')">Try it</button>
<div id="d">test</div>
You can use custom attributes
function hide(id){
var elem = document.getElementById(id);
//Store prev value
elem.setAttribute('custom-attr', elem.style.display);
elem.style.display = "none";
}
function show(id){
var elem = document.getElementById(id);
//Set prev value
elem.style.display = elem.getAttribute('custom-attr');
}
Filling in an empty value removes the inline override, so the original value is active again.
function show(id){
document.getElementById(id).style.display = "";
}
Since what you want is the default value for the element and not what's in the style sheet, you simply want to set the value to auto.
document.getElementById(id).style.display="auto"
This tells the browser to calculate what the normal display for this type of element is and to use that.
Say I have Div1 and Div2. I want to make that when a user is dragging around Div1, Div2 should also drag along. Any ideas how do I make it?
Here's what I got so far...
$(document).ready(function() {
$("#apDiv1").draggable();
$("#apDiv2").draggable(); //<- how do I link it do Div1 ?
});
EDIT ------------------------------------------------------------------
Thanks, I looked into the docs and got so far:
<script>
$(document).ready(function() {
$("#apDiv1").draggable();
});
$( "#apDiv1" ).bind( "drag", function(event, ui) {
$( "#apDiv2" ).css({ top: event.offsetY, left: event.offsetX });
</script>
Seems to be right, but... hmm, isn't' working. any ideas?
have a look at http://docs.jquery.com/UI/Draggable#event-drag to see how to bind to a draggable event. Bind the draggable event of div1 to a function that changes the coordinates of div2
Cheers.
Regarding your edit I've made some changes that can be viewed here http://jsfiddle.net/9FrXr/2/
You weren't closing the "drag" bind and instead of event.offsetY and event.offsetX I've used ui.offset.top and ui.offset.x. The drag bind has also been moved into the document.ready function.
$("#apDiv1").bind( "drag", function(event, ui) {
div.css({ top: ui.offset.top + 52, left: ui.offset.left });
});
// JavaScript Document
//This is an easy draggable javascript frameworkt
//There is no license for it so you can modify it how ever you like
//Coding started: 2011-05-28 and finished 2011-05-09
//The code can contain bugs. I only use an array to store the ID:s of the draggables
//Create an array for the draggers// I am not using an class because it is not nesesery for this easy thing
/////////////////////////////////////////////////////////////////////////////////////////////////////////
var Elements=new Array('draggable2','draggable3','draggable4','draggable5','draggable6','draggable7','draggable8','draggable9','draggable10');
//Set ID wher to do select disabeled
var textDisabling="body";
//Set drag TAG exeption//
var dragException=new Array('input','SPAN');
//////////////////////////////////////Start the framework
document.onmousemove=drag;
document.onmousedown=mouseDown;
document.onmouseup=mouseUp;
var parent;
//Offset vars//
var offsetY,offsetX;
//Setup the timeout event holder here//
var timeout=null;
//Set a var that will hold the dragged object//
var ObjectDrag;
//Set boolean vars to elerate//
var clickStage=true;
var XPos, YPos;//<--Setting up the position vars//
//////////////////////////////////////
//Get the browser name for your own needs//
//////////////////////////////////////
function getBrowserName(){
var Navigator=navigator.userAgent;
if(Navigator.indexOf("MSIE")>=0){
Navigator="MSIE";
}else if(Navigator.indexOf("Netscape")>=0){
Navigator="Netscape";
}else if(Navigator.indexOf("Firefox")>=0){
Navigator="Firefox";
}else if(Navigator.indexOf("Opera")>=0){
Navigator="Opera";
}else if(Navigator.indexOf("Safari")>=0){
Navigator="Safari";
}else{
Navigator="NULL";
}//IF
return Navigator;
}//Function
//END//
/////////////////////////////////////
//Get browser version to your neads//
/////////////////////////////////////
function getBrowserVersion(){
var browserName=getBrowserName(),
findIndex,
browserVersion;
browserVersion=navigator.userAgent;
findIndex=browserVersion.indexOf(browserName) + browserName.length+1;
browserVersion=parseFloat(browserVersion.substr(findIndex,findIndex + 3));
return browserVersion;
}//Function
//END//
function getMousePos(event){
var event=event || window.event;
//Get the position of the mouse with an offset of the top page
//////////////////////////////////////////////////////////////
if(event.pageX && event.pageY){
//We get the mouse position in newer browsers//
XPos=event.pageX;
YPos=event.pageY;
}else{
//We gat the same value as abow, but this is for older browsers//
XPos=event.clientX + document.body.scrollLeft - document.body.clientLeft;
YPos=event.clientY + document.body.scrollTop - document.body.clientTop;
}
//This is only for debugging the mouse position//
document.getElementById('X').value=XPos;/////////
document.getElementById('Y').value=YPos;/////////
return {XPos:XPos, YPos:YPos};
}
//Function for disabling text selections//
function disableTextSelection(event){
var event=event || window.event;
var object;
if(getBrowserName() != "MSIE"){object=event.target;}else{object=event.srcElement;}
if (typeof document.getElementById(textDisabling).onselectstart!="undefined"){ //IE route
document.getElementById(textDisabling).onselectstart=function(){return false}
object.onselectstart=function(){return false}
}else if (typeof document.getElementById(textDisabling).style.MozUserSelect!="undefined"){ //Firefox route
document.getElementById(textDisabling).style.MozUserSelect="none"
object.style.MozUserSelect="none"
}else{ //All other route (ie: Opera)
document.getElementById(textDisabling).onmousedown=function(){return false}
object.onmousestart=function(){return false}
}
}
//Allow text selection funtion. Call this when you do muse up//
function allowTextSelection(){
if (typeof document.getElementById(textDisabling).onselectstart!="undefined"){ //IE route
document.getElementById(textDisabling).onselectstart=function(){return true}
ObjectDrag.onselectstart=function(){return true}
}else if (typeof document.getElementById(textDisabling).style.MozUserSelect!="undefined"){ //Firefox route
document.getElementById(textDisabling).style.MozUserSelect="text"
ObjectDrag.style.MozUserSelect="text"
}else{ //All other route (ie: Opera)
document.getElementById(textDisabling).onmousedown=function(){return true}
ObjectDrag.onmousestart=function(){return true}
}
}
//Setup the global function that we will start from//
function drag(event){
var mousePos=getMousePos(event);
}
//Make an exception function //
function exception(event){
if(getBrowserName() != "MSIE"){
for(items in dragException){if(event.target.nodeName == dragException[items].toUpperCase())return {contin:false};}
}else{
for(items in dragException){if(event.srcElement.nodeName == dragException[items].toUpperCase())return {contin:false};}
}
return true;
}
//This function checks if you are pulling the click inside the element
function isInside(event){
var event=event || window.event;
var object;
if(getBrowserName() != "MSIE"){object=event.target;}else{object=event.srcElement;}
if(object.nodeName=="HTML")return false;
parent=object;
var i,l=0;
for(i=0;i<=l;i++){
if(parent.nodeName != "BODY"){
for(items in Elements){
if(Elements[items] == parent.id){
return {contin:true, id:parent};
}
}
parent=parent.parentNode;
l++;
}else{
return false;
}
}
}
//Here we get the offset position so the element will follow the mouse where you
//did (mouseDown) event. If we noe capturing the offset, the element will lie line to line with the
//mouse. NO OFFSET
function offsetObject(YPos,XPos){
offsetY=YPos-ObjectDrag.offsetTop;
offsetX=XPos-ObjectDrag.offsetLeft;
return false;
}
//Set the objects on a good z-index//
function setZIndex(event){
var event=event || window.event;
var object;
if(getBrowserName() != "MSIE"){object=event.target;}else{object=event.srcElement;}
for(items in Elements){
document.getElementById(Elements[items]).style.zIndex="1";
}
object.style.zIndex="20";
}
//Capture mouse down//
function mouseDown(event){
var event=event || window.event;
/*if(getBrowserName() != "MSIE"){ */
timeout=null;
clickStage=true;
//Store the event if it´s not null and can be dragged//
var inside=isInside(event);
if(inside.contin == true && exception(event) == true){
/*Function that disables the text selection on drag*/
disableTextSelection(event);
ObjectDrag=inside.id;
offsetObject(YPos,XPos);
//Set the z-indexes//
setZIndex(event);
moveObject();
}
/*}else{
alert("Browser is not suported");
}*/
}
//Start moving the object//
function moveObject(){
//Stor the mouse event in this var//
if(clickStage == true)timeout=setTimeout(moveObject,0);
//Change it back to true if the mouseUp event has not trigged//
clickStage=true;
//Store the event if it´s not null and can be dragged//
if(clickStage==true){
//This is the place where we set the position of the element
document.getElementById(ObjectDrag.id).style.left=XPos-offsetX+"px";
document.getElementById(ObjectDrag.id).style.top=YPos-offsetY+"px";
}
}
//Capture mouse up//
function mouseUp(event){
var event=event || window.event;
if(exception(event) == true ){
allowTextSelection();
timeout=null;
clickStage=false;
}
}
Thanks again, got it fully working on the webpage. You can see it in action by moving the menu around at www[dot]skyeye[dot]cc .
<script>
$(function() {
$("#apDiv3").draggable();
$("#apDiv3").bind("drag", function(event, masterdrag) {
$("#apDiv5").css({ top: masterdrag.offset.top, left: masterdrag.offset.left-20 });
});
});
</script>