js - swap image on click - javascript

I'm trying to replace one div with another and turn the others off:
JS
function imgToSWF1() {
document.getElementById('movie-con2 movie-con3 movie-con4').style.display = 'none';
document.getElementById('movie-con').style.display = 'block';
}
function imgToSWF2() {
document.getElementById('movie-con movie-con3 movie-con4').style.display = 'none';
document.getElementById('movie-con2').style.display = 'block';
}
function imgToSWF3() {
document.getElementById('movie-con movie-con2 movie-con4').style.display = 'none';
document.getElementById('movie-con3').style.display = 'block';
}
function imgToSWF4() {
document.getElementById('movie-con movie-con2 movie-con3').style.display = 'none';
document.getElementById('movie-con4').style.display = 'block';
}
HTML
<span onmouseover="src=imgToSWF1();"><div class="numbers">01</div></span>
<span onmouseover="src=imgToSWF2();"><div class="numbers">02</div></span>
<span onmouseover="src=imgToSWF3();"><div class="numbers">03</div></span>
<span onmouseover="src=imgToSWF4();"><div class="numbers">04</div></span>
I can't seem to get this to work and I believe that targetting multiple ID's isn't possible like this? Anyway any advice would be smashing - thanks!

You're correct that you cannot supply multiple ids to document.getElementById(). Instead, you can grab them all individually using an array. There are many ways to accomplish what you are trying to do. This is a straightforward method based on iterating through the array of the elements to hide and hiding all of them.
This method expects you to define the array of nodes to hide in each of your functions, and so is non-ideal.
// Example:
function imgToSWF1() {
var nodes = ['movie-con2', 'movie-con3', 'movie-con4'];
// Loop over and hide every node in the array
for (var i=0; i<nodes.length; i++) {
document.getElementById(nodes[i]).style.display = 'none';
}
document.getElementById('movie-con').style.display = 'block';
}
Better:
This can be refactored into one function, however. Make one function which recieves the node you want to show as an argument. Hide the others. The array should contain all nodes that may be hidden in any circumstance, and be defined at a higher scope than the function.
// Array holds all nodes ids
var nodes = ['movie-con', 'movie-con2', 'movie-con3', 'movie-con4'];
// Function receives a node id which will be shown
function imageToSWF(nodeId) {
// Loop over and hide every node in the array
for (var i=0; i<nodes.length; i++) {
document.getElementById(nodes[i]).style.display = 'none';
}
// And unhide/show the one you want, passed as an argument
document.getElementById(nodeId).style.display = 'block';
}
Call as:
<span onmouseover="imageToSWF('movie-con');"><div class="numbers">01</div></span>
<span onmouseover="imageToSWF('movie-con2');"><div class="numbers">02</div></span>
<span onmouseover="imageToSWF('movie-con3');"><div class="numbers">03</div></span>
<span onmouseover="imageToSWF('movie-con4');"><div class="numbers">04</div></span>

You have to target one element at a time with document.getElementById, eg. document.getElementById('movie-con2').style.display='none'; document.getElementById('movie-con3').style.display='none';
etc, etc.
You could also use Jquery siblings selector to show or hide all elements that are siblings within a parent tag.

You definitely can't do that in straight up javascript. The document.getElementById function only returns a single element from the DOM.
Some docs can be had here:
http://www.w3schools.com/jsref/met_doc_getelementbyid.asp
https://developer.mozilla.org/en-US/docs/DOM/document.getElementById
If you were to use a toolkit like jQuery you could do something like:
$('div[id^="movie-con"]').hide(); // hide everything
$('div["movie-con"' + index + "]").show(); // show the one we want
Since you're not using jQuery it's not quite as easy. Something like:
var matches = document.getElementById("containerDiv").getElementsByTagName("img");
for( var i = 0; i < matches.length; i++ )
matches[i].style.display = "none";
document.getElementById('movie-con' + index).style.display = "block";

Related

How to target a data-ref with a specific value and add a style using javascript

I want to target a data-ref with a specific value and add an inline style="display:none;" to it.
How can this be achived? Can someone help me please?
This is how it looks:
<div data="{test-bubble}}" data-ref="bubbles[test-link.com/test]" class="bubbles" state="default">
</div>
I tried this but it does not work:
var bubbleremoval = document.querySelector('[data-ref="bubbles[test-link.com/test]"]')
bubbleremoval.style.display = "none";
"""Your code should work if you are applying to a single element since query selector returns one element but for several elements you could fetch by classname and loop through the elements and remove display for each"""
var bubbleremoval = document.getElementsByClassName('bubbles')
for (let i = 0; i < bubbleremoval.length; i++) {
bubbleremoval[i].style.display = "none";
}

How to select an element with specific css value in javascript

I want to select an element if it has a css as display block then do this function. If the element has the css as display block then remove ('hide') class from the header class.. This is what I want to do.. Any help?
Well, there are two solutions depending on what you want:
Solution 1
Looping through all elements and removing hide class from the current element if it has display block value in its style.
var elements = document.getElementsByTagName("*");
for(let i = 0; i < elements.length; i++) {
if(elements[i].style.display == "block") {
elements[i].classList.remove("hide");
}
}
Solution 2
Getting the reference of the element via HTML id.
var element = document.getElementById("YourElementID");
if(element.style.display == "block") {
element.classList.remove("hide");
}
You can define an id like this in your HTML file:
<div id="YourElementID">Div</div>
I am assuming that you want to determine if the element has the "hide" class by checking its display style. you don't need to do that, you can easily check its class list by using the following code:
element.classList.contains("hide");
There are several ways of collecting all the elements with display: block and i am not sure, which one performs best - or whether it performs good at all.
If you want all the Element instances of the page, which have a computed style of display: block you can do something like:
var $els = Array.from(document.body.querySelectorAll('*')).filter(function($el) {
return getComputedStyle($el).display === 'block';
});
Or ES6:
const $els = Array.from(document.body.querySelectorAll('*')).filter($el => getComputedStyle($el).display === 'block');
If you want the Element instances which have display: block literally set in the style-attribute, you have to do something like this:
var $els = Array.from(document.body.querySelectorAll('*')).filter(function($el) {
return $el.style.display === 'block';
});
I think it would perform better, if the selector in querySelectorAll() would be a little more specific.
Another option would be to use the TreeWalker API, but then you have to do a mutation, because you have to iterate over all the elements and push them to an array:
var $els = [];
walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT);
while (walker.nextNode()) {
if (getComputedStyle(walker.currentNode).display === 'block') {
$els.push(walker.currentNode);
}
}
Once you have all your elements, you can do something with them.
A little bit more information would be helpful, especially what exactly you want to achieve, once you have the elements, because then i could also provide more help. Maybe provide a code example?

Taming the Select - Don't replace disabled OPTION

I have found a great piece of Javascript called Taming Select. I know it's quite old but has worked absolute wonders with rendering the < select > input into a UL dropdown list.
My problem is that my < select > DOM element has dynamically disabled < option > children, yet this piece of code does not discern whether it is disabled or not.
I was wondering a couple of things:
How do I get Javascript to identify disabled < options >?
Should I delete the DOM element completely or inject CSS classes into the newly made list items to disable them with user-select and pointer-events?
I have been on the search for nearly 8 hours and I can't seem to figure out how to do number 1 on my list.
I have tried getElementsByTagName('option').disabled and other variations of getElementsByTagName and nothing happens; even when I modify some examples in W3Schools.
Below is the code for TamingSelect:
function tamingselect()
{
if(!document.getElementById && !document.createTextNode){return;}
// Classes for the link and the visible dropdown
var ts_selectclass='turnintodropdown'; // class to identify selects
var ts_listclass='turnintoselect'; // class to identify ULs
var ts_boxclass='dropcontainer'; // parent element
var ts_triggeron='activetrigger'; // class for the active trigger link
var ts_triggeroff='trigger'; // class for the inactive trigger link
var ts_dropdownclosed='dropdownhidden'; // closed dropdown
var ts_dropdownopen='dropdownvisible'; // open dropdown
/*
Turn all selects into DOM dropdowns
*/
var count=0;
var toreplace=new Array();
var sels=document.getElementsByTagName('select');
for(var i=0;i<sels.length;i++){
if (ts_check(sels[i],ts_selectclass))
{
var hiddenfield=document.createElement('input');
hiddenfield.name=sels[i].name;
hiddenfield.type='hidden';
hiddenfield.id=sels[i].id;
hiddenfield.value=sels[i].options[0].value;
sels[i].parentNode.insertBefore(hiddenfield,sels[i])
var trigger=document.createElement('a');
ts_addclass(trigger,ts_triggeroff);
trigger.href='#';
trigger.onclick=function(){
ts_swapclass(this,ts_triggeroff,ts_triggeron)
ts_swapclass(this.parentNode.getElementsByTagName('ul')[0],ts_dropdownclosed,ts_dropdownopen);
return false;
}
trigger.appendChild(document.createTextNode(sels[i].options[0].text));
sels[i].parentNode.insertBefore(trigger,sels[i]);
var replaceUL=document.createElement('ul');
for(var j=0;j<sels[i].getElementsByTagName('option').length;j++)
{
var newli=document.createElement('li');
var newa=document.createElement('a');
newli.v=sels[i].getElementsByTagName('option')[j].value;
newli.elm=hiddenfield;
newli.istrigger=trigger;
newa.href='#';
newa.appendChild(document.createTextNode(
sels[i].getElementsByTagName('option')[j].text));
newli.onclick=function(){
this.elm.value=this.v;
ts_swapclass(this.istrigger,ts_triggeron,ts_triggeroff);
ts_swapclass(this.parentNode,ts_dropdownopen,ts_dropdownclosed)
this.istrigger.firstChild.nodeValue=this.firstChild.firstChild.nodeValue;
return false;
}
newli.appendChild(newa);
replaceUL.appendChild(newli);
}
ts_addclass(replaceUL,ts_dropdownclosed);
var div=document.createElement('div');
div.appendChild(replaceUL);
ts_addclass(div,ts_boxclass);
sels[i].parentNode.insertBefore(div,sels[i])
toreplace[count]=sels[i];
count++;
}
}
/*
Turn all ULs with the class defined above into dropdown navigations
*/
var uls=document.getElementsByTagName('ul');
for(var i=0;i<uls.length;i++)
{
if(ts_check(uls[i],ts_listclass))
{
var newform=document.createElement('form');
var newselect=document.createElement('select');
for(j=0;j<uls[i].getElementsByTagName('a').length;j++)
{
var newopt=document.createElement('option');
newopt.value=uls[i].getElementsByTagName('a')[j].href;
newopt.appendChild(document.createTextNode(uls[i].getElementsByTagName('a')[j].innerHTML));
newselect.appendChild(newopt);
}
newselect.onchange=function()
{
window.location=this.options[this.selectedIndex].value;
}
newform.appendChild(newselect);
uls[i].parentNode.insertBefore(newform,uls[i]);
toreplace[count]=uls[i];
count++;
}
}
for(i=0;i<count;i++){
toreplace[i].parentNode.removeChild(toreplace[i]);
}
function ts_check(o,c)
{
return new RegExp('\\b'+c+'\\b').test(o.className);
}
function ts_swapclass(o,c1,c2)
{
var cn=o.className
o.className=!ts_check(o,c1)?cn.replace(c2,c1):cn.replace(c1,c2);
}
function ts_addclass(o,c)
{
if(!ts_check(o,c)){o.className+=o.className==''?c:' '+c;}
}
}
window.onload=function()
{
tamingselect();
// add more functions if necessary
}
Any help would be greatly appreciated. I have very very little Javascript experience (to be honest, the closest I have come to studying it was ActionScript 10 years ago).
Thanks in advance.
Michael
You're looking for the .hasAttribute() function which returns a bool.
ie. el.hasAttribute('disabled').
https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttribute
As mentioned in the comment, to actually iterate through the options to check for the attribute you should do the following:
// returns an array like HTMLCollection of the elements that match the
// tag
let options = document.getElementsByTagName('option')
// uses the array method forEach on the HTMLCollection.
// note that HTMLCollections do not natively have the forEach method
// but still act behave normal arrays when using iteration.
Array.prototype.forEach.call( options, el => {
el.hasAttribute('disabled')
})

How do I filter an unorderded list to display only selected items using Javascript?

I have this JSFiddle where I am trying to make it so that the items in an unordered list are visible only if the option selected in a drop down matches their class. List items may have multiple classes, but so long as at least one class matches, the item should be made visible.
The Javascript looks like this:
function showListCategories() {
var selection = document.getElementById("listDisplayer").selectedIndex;
var unHidden = document.getElementsByClassName(selection);
for (var i = 0; i < unHidden.length; i++) {
unHidden[i].style.display = 'visible';
}
};
The idea is that it gets the current selection from the drop down, creates an array based on the matching classes, then cycles through each item and sets the CSS to be hidden on each one.
However, it's not working. Can anyone tell me where I'm going wroing?
Note that I haven't yet coded the "show all" option. I think I'll probably be able to figure that out once I have this first problem solved.
In your fiddle change load script No wrap - in <head>.
Just change your function like following
function showListCategories() {
var lis = document.getElementsByTagName('li');
for (var i = 0; i < lis.length; i++) {
lis[i].style.display = 'none';
}
//above code to reset all lis if they are already shown
var selection = document.getElementById("listDisplayer").value;
lis = document.getElementsByClassName(selection);
for (var i = 0; i < lis.length; i++) {
lis[i].style.display = 'block';
}
};
and in css it should be none not hidden
.cats, .rats, .bats {
display: none;
}
If you want to show all li when showAll is selected, add all classes to all lis.
You have a few things going on. First, your fiddle is not setup correctly, if you open the console you'll see:
Uncaught ReferenceError: showListCategories is not defined
This means that the function doesn't exist at the point you attach the event or that the function is out of scope, because by default jsFiddle will wrap your code in the onLoad event. To fix it you need to load the script as No wrap - in <body>.
Second, there's no such thing as a display:visible property in CSS. The property you want to toggle is display:none and display:list-item, as this is the default style of <li> elements.
Now, to make this work, it is easier if you add a common class to all items, let's say item, that way you can hide them all, and just show the one you want by checking if it has a certain class, as opposed to querying the DOM many times. You should cache your selectors, it is not necessary to query every time you call the function:
var select = document.getElementById('listDisplayer');
var items = document.getElementsByClassName('item');
function showListCategories() {
var selection = select.options[select.selectedIndex].value;
for (var i=0; i<items.length; i++) {
if (items[i].className.indexOf(selection) > -1) {
items[i].style.display = 'list-item';
} else {
items[i].style.display = 'none';
}
}
}
Demo: http://jsfiddle.net/E2DKh/28/
First there is no property in Css like display:hidden; it should be display: none;
here is the solution please not that i am doing it by targeting id finished
Js function
var selection = document.getElementById("listDisplayer");
var list = document.getElementsByTagName('li');
selection.onchange = function () {
var value = selection.options[selection.selectedIndex].value; // to get Value
for (var i = 0; i < list.length; i++) {
if (list[i].className.indexOf(value) > -1) {
list[i].style.display = "list-item";
} else {
list[i].style.display = "none"
}
}
}
css Code
.cats, .rats, .bats {
display: none;
}
JSFIDDLE
You have many things wrong in your code and a wrong setting in the jsFiddle. Here's a working version that also implements the "all" option:
Working demo: http://jsfiddle.net/jfriend00/5Efc5/
function applyToList(list, fn) {
for (var i = 0; i < list.length; i++) {
fn(list[i], list);
}
}
function hide(list) {
applyToList(list, function(item) {
item.style.display = "none";
});
}
function show(list) {
applyToList(list, function(item) {
item.style.display = "block";
});
}
function showListCategories() {
var value = document.getElementById("listDisplayer").value;
var itemList = document.getElementById("itemList");
var items = itemList.getElementsByTagName("li");
if (value === "all") {
show(items);
} else {
// hide all items by default
hide(items);
show(itemList.getElementsByClassName(value));
}
}
Changes made:
You have to fetch the .value of the select to see what the value was of the option that was picked. You were using the selectedIndex which is just a number.
A common technique for displaying only a set of objects is to hide all of them, then show just the ones you want. Since the browser only does one repaint for the entire operation, this is still visually seamless.
When finding items that match your class, you should be searching only the <ul>, not the entire document. I added an id to that <ul> tag so it can be found and then searched.
To save code, I added some utility functions for operating on an HTMLCollection or nodeList.
Tests for the "all" option and shows them all if that is selected
Changed the jsFiddle to the Head option so the code is available in the global scope so the HTML can find your change handler function.
Switched style settings to "block" and "none" since "visible" is not a valid setting for style.display.

get element after page loads

how do i call a function to count the number of divs with an id of 'd1' after the page loads. right now i have it in my section but doesnt that execute the script before anything in the loads? because it works if i put the code below the div tags...
Firstly there should be at most one because IDs aren't meant to be repeated.
Second, in straight Javascript you can call getElementById() to verify it exists or getElementsByTagName() to loop through all the divs and count the number that match your criteria.
var elem = document.getElementById("d1");
if (elem) {
// it exists
}
or
var divs = document.getElementsByTagName("div");
var count = 0;
for (var i = 0; i < divs.length; i++) {
var div = divs[i];
if (div.id == "d1") {
count++;
}
}
But I can't guarantee the correct behaviour of this because like I said, IDs are meant to be unique and when they're not behaviour is undefined.
Use jQuery's document.ready() or hook up to the onLoad event.
well an ID should be unique so the answer should be one.
you can use <body onload='myFunc()'> to call a script once the DOM is loaded.
You need to have the function tied to the onload event, like so:
window.onload = function() {
var divElements = document.getElementById("d1");
var divCount = divElements.length;
alert(divCount);
};
For the record, you should only have one div with that ID, as having more than one is invalid and may cause problems.

Categories

Resources