Adding a class using JavaScript - javascript

Could anyone give me a hand with the following JavaScript issue.
I am trying to come up with a function that adds a class to a div that has a specified class.
I have tried to come up with something based on what a few people have said but it doesn't seem to work.
http://jsfiddle.net/samsungbrown/vZ9Hu/
Where am I going wrong?
Thanks
function toggleClass(matchClass,content) {
var elems = document.getElementsByTagName('*'),i;
for (i in elems) {
if((" "+elems[i].className+" ").indexOf(" "+matchClass+" ") > -1) {
elems[i].classList.toggle(content);
}
}
}
window.onload = function () {
toggleClass("col-left","display");
}

Because of some quirks in jsFiddle your code doesn't run. Remove the .onload wrapper and your code runs. See: http://jsfiddle.net/vZ9Hu/1/

Related

How to set a JS variable from a CSS style

I've made a bunch of JavaScript functions to show, hide and populate various elements on a zooming menu. All seem to working except for one which I need the function to only run if a CSS setting is a specific value (width of 195%). I am very new to JavaScript so there may be more than one issue here.
<script>
function zoomShowF2() {
var widthNow = document.getElementById('svg1').style.width;
if widthNow = '195%' {
document.getElementById('zoomTitle').style.display = 'flex';
else
document.getElementById('zoomTitle').style.display = 'none';
}}</script>
You need to use comparison operators write the if statement as follows
if (widthNow == '195%') {
as the single = is assigning the value not comparing it
There are a few issues with your syntax:
function zoomShowF2() {
var widthNow = document.getElementById('svg1').style.width;
if (widthNow === '195%') {
document.getElementById('zoomTitle').style.display = 'flex';
} else {
document.getElementById('zoomTitle').style.display = 'none';
}
}
Thanks everyone. It works now with a combination of the changes suggested. I assume my curly braces are all in 'tidy' positions?
EDIT. I've adjusted the curly brace positions to as per Ed's layout.
Thanks all!
Your code does not called when the element changes it size or width. You must put all your code inside window.onresize event.
var displayOutput = document.getElementById("display-option");
function reportWindowSize() {
displayOutput.text = document.getElementById("element-to-check").style.width;
}
window.onresize = reportWindowSize;
<p id="element-to-check">Resize the browser window to fire the <code>resize</code> event.</p>
<p>Display: <span id="display-option"></span></p>

javascript/htmlDOM display element while hiding the others

So I have written this clickDisplay function that displays certain elements on click, it works fine, yes, but obviously I needed a feature that would hide all the other elements, because they are supposed to be displayed in the same field, so right now they kind stack on top of eachother
this is what I came up with, but it sorta doesn't work and I don't know why
const pages = ['watch','chars','seasons','songs']
function clickHide(element){
document.getElementById(element).style.display = 'none';
}
function clickDisplay(element){
document.getElementById(element).style.display = 'block';
for(let x = 0 ; x < pages.length ; x++){
if (pages[x]!=element){clickHide(pages[x]);}
}
}
While it sounds like you solved your own problem, I started putting together code before you posted, so I'll throw it up here for you. :)
const pages = ['watch', 'chars', 'seasons', 'songs']
function clickHide (el) {
pages.forEach((pel) => {
setElement(pel, pel === el ? 'none' : 'block')
})
}
function setElement(el, attr) {
document.getElementById(el).style.display = attr
}
with the html having this:
onclick="clickHide('watch')" // or 'chars' 'seasons' or 'songs'
Oh wait, I don't know why but this suddenly works now. I only changed the placeholder text and refreshed the page
But I'm sure that this still is a stupid solution

specific function in Javascript

I have a function took on a tutorial, it works fine with one only element but I want to use it with some elements and I do not know enough about Javascript to do so.
This is my function :
var elements = document.getElementsByClassName('boules');
for (var i = 0; i < elements.length; i++) {
gameAccel(elements[i]);
}
function gameAccel(sphere) {
var x=20,y=300,vx=0,vy=0,ax=0,ay=0;
if(window.DeviceMotionEvent!=undefined){
window.ondevicemotion=function(e){
ax=event.accelerationIncludingGravity.x*3;
ay=event.accelerationIncludingGravity.y*3;
}
monInterval = setInterval(function(){
var landscapeOrientation=window.innerWidth/window.innerHeight>1;
if(landscapeOrientation){
vx=vx+ay;
vy=vy+ax;
}else{
vy=vy-ay;
vx=vx+ax;
}
vx=vx*0.98;
vy=vy*0.98;
y=parseInt(y+vy/50);
x=parseInt(x+vx/50);
boundingBoxCheck();
sphere.style.top=y+"px";
sphere.style.left=x+"px";
},25);
}
function boundingBoxCheck(){
if(x<0){x=0;vx=-vx;}
if(y<0){y=0;vy=-vy;}
if(x>document.documentElement.clientWidth-40){
x=document.documentElement.clientWidth-40;
vx=-vx;
}
if(y>document.documentElement.clientHeight-40){
y=document.documentElement.clientHeight-40;
vy=-vy;
}
}
}
I have one element with "boules" class, it works, if I have several elements with "boules" class it doesn't works.
This function is used on mobile device with gyroscope. (this is the basic example http://www.albertosarullo.com/demos/accelerometer/).
Someone can explain me why and how I can correct that ?
Thanks a lot.
You are overwriting window.ondevicemotion and monInterval every time you call the function. Only the last handler will be triggered. Instead, use addEventListener to attach multiple handlers and a local variable.
You have overwrites window.ondevicemotion handler in every loop. It must works only for last handler.

JavaScript/jQuery: hasDescendant / hasAncestor

Hilariously, I'm having incredible difficulty finding any half-good way to determine whether or not an HTML element is inside another one or not -- which seems like it should be a basic core feature of traversing and analyzing the HTML DOM. I was immensely surprised and disappointed that the "hasDescendant" (or likewise) method is missing.
I'm trying to do this:
var frog = $('#frog');
var walrus = $('#walrus');
if (frog.hasDescendant(walrus)) console.log("Frog is within walrus.");
else console.log("Frog is outside walrus.");
I've tried to reproduce what I'm looking for with many jQuery combinations.
walrus.is(frog.parents());
walrus.has(frog);
walrus.find(' *').has(frog);
frog.is(walrus.find(' *'));
I haven't found a working solution yet.
[edit]
Solution: walrus.has(frog)
Alternate: if (walrus.has(frog)) { doStuff(); }
Alternate: var booleanResult = walrus.has(frog).length>0;
//Chase.
jQuery has just the function for this: jQuery.contains: "Check to see if a DOM element is within another DOM element."
Demo (live copy):
HTML:
<p id="frog">Frog <span id="walrus">walrus</span></p>
JavaScript:
jQuery(function($) {
var frog = $("#frog"),
walrus = $("#walrus");
display("frog contains walrus? " + $.contains(frog[0], walrus[0]));
display("walrus contains frog? " + $.contains(walrus[0], frog[0]));
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
Use
if (walrus.has(frog).length) {
// frog is contained in walrus..
}
Demo at http://jsfiddle.net/gaby/pZfLm/
An alternative
if ( $('#frog').closest('#walrus').length ){
// frog is contained in walrus..
}
demo at http://jsfiddle.net/gaby/pZfLm/1/
If you wanted to write your own function you could do it without jQuery, perhaps something like this:
function isAncestor(ancestor, descendent) {
while ((descendent = descendent.parentNode) != null)
if (descendent == ancestor)
return true;
return false;
}

IE8 tinyMCE .NET insert image

Solution: The problem below was caused by a Divx javascript that overwrote a core javascript function. Thanks to aeno for discovering this and shame on the Divx coder who did that!
Problem: Clicking the insert image button in the tinymce toolbar does nothing in IE8.
Description: Bear with me here. I don't think the issue is with tinymce and it's probably the fault of IE8, but I need help from someone wiser than me in solving the final piece of the puzzle to figure out who is responsible for this...
So basically I'm using tinyMCE with Visual Studio 2010 and I get the problem as described above. So I switch to the tinyMCE source code to debug this. The problem seems to happen in this piece of the code in the inlinepopups/editor_plugin_src.js, line 358:
_addAll : function(te, ne) {
var i, n, t = this, dom = tinymce.DOM;
if (is(ne, 'string'))
te.appendChild(dom.doc.createTextNode(ne));
else if (ne.length) {
te = te.appendChild(dom.create(ne[0], ne[1]));
for (i=2; i<ne.length; i++)
t._addAll(te, ne[i]);
}
},
the exact line of code being,
te = te.appendChild(dom.create(ne[0], ne[1]));
In IE8 te becomes null because te.appendChild returns nothing.
To give some background on the the code, te is a DOM.doc.body object and ne seems to be a json object containing the structure of the inline popup object that needs to be created.
So back to the code.. this works with all other browsers no problem. So I step into the function appendChild and I'm brought to some "JScript - script block [dynamic]" file that does the unthinkable. It overrides the doc.body.appendChild function... You can see it below,
code cut out
...
var appendChildOriginal = doc.body.appendChild;
doc.body.appendChild = function(element)
{
appendChildOriginal(element);
var tag = element.tagName.toLowerCase();
if ("video" == tag)
{
ProcessVideoElement(element);
}
}
...
code cut out
Here we can obviously see what went wrong. Of course te.appendChild returns nothing... it has NO RETURN STATEMENT!
So the final piece to this puzzle is wtf is this dynamic script block? I can't for the love of god figure out where this script block is coming from (VS2010 is not helping). My deepest suspicions are that this is IE8 in built? Can anyone shed some light on this? Below I'm providing a little bit more of this mysterious script block in case anyone can figure out where it's from. I can promise you something right now, it doesn't belong to any of the scripts in our project since we've done a search and we turn up with nothing.
var doc;
var objectTag = "embed";
// detect browser type here
var isInternetExplorer = (-1 != navigator.userAgent.indexOf("MSIE"));
var isMozillaFirefox = (-1 != navigator.userAgent.indexOf("Firefox"));
var isGoogleChrome = (-1 != navigator.userAgent.indexOf("Chrome"));
var isAppleSafari = (-1 != navigator.userAgent.indexOf("Safari"));
// universal cross-browser loader
if (isInternetExplorer)
{
// use <object> tag for Internet Explorer
objectTag = "object";
// just execute script
ReplaceVideoElements();
}
else if (isMozillaFirefox)
{
// listen for the 'DOMContentLoaded' event and then execute script
function OnDOMContentLoadedHandled(e)
{
ReplaceVideoElements();
}
window.addEventListener("DOMContentLoaded", OnDOMContentLoadedHandled, false);
}
else if (isGoogleChrome)
{
// just execute script
ReplaceVideoElements();
}
else if (isAppleSafari)
{
// listen for the 'DOMContentLoaded' event and then execute script
function OnDOMContentLoadedHandled(e)
{
ReplaceVideoElements();
}
window.addEventListener("DOMContentLoaded", OnDOMContentLoadedHandled, false);
}
function MessageHandler(event)
{
//window.addEventListener("load", OnLoad, false);
}
// replacing script
function ReplaceVideoElements()
{
if (isMozillaFirefox)
{
doc = window.content.document;
}
else
{
doc = document;
}
// set up DOM events for Google Chrome & Mozilla Firefox
if (isMozillaFirefox || isGoogleChrome || isAppleSafari)
{
doc.addEventListener("DOMNodeInserted", onDOMNodeInserted, false);
doc.addEventListener("DOMNodeInsertedIntoDocument", onDOMNodeInsertedIntoDocument, false);
}
// HACK : override appendChild, replaceChild, insertBefore for IE, since it doesn't support DOM events
if (isInternetExplorer)
{
var appendChildOriginal = doc.body.appendChild;
doc.body.appendChild = function(element)
{
appendChildOriginal(element);
var tag = element.tagName.toLowerCase();
if ("video" == tag)
{
ProcessVideoElement(element);
}
}
var replaceChildOriginal = doc.body.replaceChild;
doc.body.replaceChild = function(element, reference)
{
replaceChildOriginal(element, reference);
var tag = element.tagName.toLowerCase();
if ("video" == tag)
{
ProcessVideoElement(element);
}
}
var insertBeforeOriginal = doc.body.insertBefore;
doc.body.insertBefore = function(element, reference)
{
insertBeforeOriginal(element, reference);
var tag = element.tagName.toLowerCase();
if ("video" == tag)
{
ProcessVideoElement(element);
}
}
}
...
code cut out
HI,
I'm dealing with the exact same problem occuring when opening a prettyPhoto gallery...
I have no idea where this "script block" is coming from, but it definitely causes the error.
So, does anyone know anything on this suspicious script block?
Thanks,
aeno
edit:
A little more googling shed some light onto it: The mentioned script block comes from the DivX plugin that's installed in InternetExplorer. Deactivating the DivX plugin suddenly solved the problem and prettyPhoto opens quite smooth :)
Now I have to figure out whether the DivX developers have bug tracker...

Categories

Resources