I am trying use this function that changes the class and onclick of another element.
partner = this.id + 'Content';
document.getElementById(partner).className = 'newswrapper';
document.getElementById(partner).onclick = function(){ clickNews(this); } ;
the id of the element with the onclick looks like this.
echo'<div id="newsSlide'.$counter.'" class="newsimage"
onclick="clickNews(this)"
style='."'".'background-image:url("../img/'.$row['image'].'")'".'>';
and the element that is supposed to have its class changed looks like this
echo'<div id="newsSlide'.$counter.'Content" class="newswrapper">';
getting the error
Uncaught TypeError: Cannot set property 'className' of null
echo'<script>';
echo"function clickNews(id)
{
var y = document.getElementsByClassName('newswrapper');
var x = document.getElementsByClassName('newswrapper2');
var length = y.length,
element = null;
for (var i = 0; i < length; i++) {
element = y[i];
element.className = 'newswrapper2';
}
var length = x.length,
element = null;
for (var i = 0; i < length; i++) {
element = x[i];
element.className = 'newswrapper2';
}
partner = this.id + 'Content';
document.getElementById(partner).className = 'newswrapper';
document.getElementById(partner).onclick = function(){ clickNews(this); } ;
}";
echo'</script>';
the html can be found
here : http://pastebin.com/6xBNBQwZ
or you can use the HTML inspector on the actual page here
here : http://www.uk-sf.com/indextest.php
You're missing document.:
document.getElementById(partner).className = 'newswrapper';
getElementById is a method of the document, not the window ;)
Your this.id in partner = this.id + 'Content' is refer to global variable id on window object not the id to your element, and becouse ther is not global variable the partner variable looks like that undefinedContent
So change onclick="clickNews(this.id)" and than use id from arguments
function clickNews(id)
{
partner = id + 'Content'; // use id form arguments
}
And fiddle with simple example
Related
// function to read all attributes
function get_attributes(source_node) { // source of attributes
var i, attribute, size, tab = [];
attribute = { name: "", value: "" } // new type
size = source_node.attributes.length; // reading size
for (i = 0; i < size; i++) {
attribute.name = source_node.attributes[i].name;
attribute.value = source_node.attributes[i].value;
tab[i] = attribute; //putting attribute into table
alert(tab[i].name + " - " + tab[i].value);
}
return tab; //returning filled table
}
Problem is, table (tab) consists only last red parameter :(
Anyone?
Source_node can be anything. ie "document.body"
it works if declared inside loop
...
for (i = 0; i < size; i++) {
VAR attribute =[];
attribute.name = source_node.attributes[i].name;
attribute.value = source_node.attributes[i].value;
tab[i] = attribute; //putting attribute into table
}
....
I'm looping through some elements by class name, and adding event listeners to them. I then grab the id of the selected element (in this case "tom"), and want to use it to find the value of "role" in the "tom" object. I'm getting undefined? can anyone help?
var highlightArea = document.getElementsByClassName('highlightArea');
for (var i = 0; i < highlightArea.length; i++) {
highlightArea[i].addEventListener("mouseover", showPopup);
highlightArea[i].addEventListener("mouseover", hidePopup);
}
function showPopup(evt) {
var tom = { title:'tom', role:'full stack man' };
var id = this.id;
var role = id.role;
console.log(role)
}
You are not selecting the elements correctly, the class is hightlightArea and you are querying highlightArea (missing a 't'), so, no elements are found (you can easily discover that by debugging or using console.log(highlightArea) that is the variable that holds the elements found.
Just because the id of an element is the same name as a var, it doesn't mean that it have the properties or attributes of the variable... So when you get the Id, you need to check which one is and then get the variable that have the same name.
Also, you are adding the same listener two times mouseover that way, just the last would work, it means just hidePopup. I changed to mouseenter and mouseleave, this way will work correctly.
After that, you will be able to achieve your needs. Below is an working example.
var highlightArea = document.getElementsByClassName('hightlightArea');
var mypopup = document.getElementById("mypopup");
var tom = { title:'tom', role:'marketing'};
var jim = { title:'jim', role:'another role'};
for (var i = 0; i < highlightArea.length; i++) {
highlightArea[i].addEventListener("mouseenter", showPopup);
highlightArea[i].addEventListener("mouseleave", hidePopup);
}
function showPopup(evt) {
let ElemId = this.id;
let role;
let title;
if (ElemId == 'tom'){
role = tom.role;
title = tom.title;
}else if (ElemId == 'jim'){
role = jim.role;
title = jim.title;
}
let iconPos = this.getBoundingClientRect();
mypopup.innerHTML = role;
mypopup.style.left = (iconPos.right + 20) + "px";
mypopup.style.top = (window.scrollY + iconPos.top - 60) + "px";
mypopup.style.display = "block";
}
function hidePopup(evt) {
mypopup.style.display = "none";
}
<div class="hightlightArea" id="jim">Div Jim</div>
<div class="hightlightArea" id="tom">Div Tom</div>
<div id="mypopup"></div>
in your function 'showPopup' you have this:
var id = this.id
but this.id is not defined. You probably meant to write this:
var title = dom.title;
As opposed to setting individual functions to each element's click event, I would like to iterate elements and assign based on id or whatever?
document.getElementById('measure').onclick = function() { clickMe(1); };
How would I approach this?
In the past I've done something along these lines:
var setClickOnElements = function(selector) {
$(selector).each(function() {
$(this).click(function(event) {
// behaviour on click
});
});
};
...where selector is a class selector, e.g. .my-class. Within the callback passed to each you can get at other properties of the selected elements, e.g. id etc. If you add that class to the elements you'd like to set a click function and call setClickOnElements('.my-class'); on load, you should be good to go!
EDIT: The above uses jQuery. If you're restricted to pure Javascript, you could use one of the methods described in John Resig's post on implementations of getElementByClass: http://ejohn.org/blog/getelementsbyclassname-speed-comparison/
Here's an example (using Dustin Diaz's method from http://www.dustindiaz.com/getelementsbyclass):
var getElementsByClass = function(searchClass,node,tag) {
var classElements = new Array();
if ( node == null )
node = document;
if ( tag == null )
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
var setClickOnElements = function(className) {
var elements = getElementsByClass(className);
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
element.onclick = function(event) {
// click behaviour here
};
}
};
I am creating div tags on the fly inside a for loop.
The divs are outputted nicely like a chess table and there is a unique id for each.
I just don't know how to retrieve it in its click function. 'this.id' or $(this).id doesn't work (I generally use it in $.each methods).
*How could I retrieve/refer to the id inside the click function ? *
I've posted a bigger code part width variables, but the main part is this:
$("<div/>", {
class: gridClass,
id: cardID,
click: function(e) {
alert(this.id);
}
});
more from the code:
var init = function() {
//variable declaration
var GRID_WIDTH = 2,
GRID_HEIGHT = 2,
var FACE_DOWN = 0;
var cont = $("<div/>", {
id: 'container'
});
var c1 = "card";
var c2 = "card cardfirstInRow";
var gridClass = "";
var cardID = "";
// end variable declaration
// creating DIV-s on the fly
for (var x = 0; x < GRID_WIDTH; x++) {
for (var y = 0; y < GRID_HEIGHT; y++) {
y === 0 ? gridClass = 'card cardfirstInRow' : gridClass = 'card';
cardID = controller.getCardID(); //returns a unique number converted to string
$("<div/>", {
class: gridClass,
id: cardID,
click: function(e) {
alert(this.id);
}
}).appendTo(cont);
}
}
}
The problem is in your click function, not your creation of the div function. Because you are adding the div's to the DOM you need to use event delegation to capture the click event when it bubbles up -
$('body').on('click', 'div' function() {
console.log( this.id );
});
e.target gives you the element (javascript object)
To get the id just use
var elemId = e.target.id;
try this
$(this).attr('id');
that is the method that returns an attribute value of an element using jQuery
Here is the Fiddle
I am writing a number of functions to show and hide various divs on a page by applying style classes called "hidden" and "visible" using setAttribute. This function is intended to hide several divs at once. The ID of each div to be given the class "hidden" is listed in an array.
Each div may have more than one class, so when a div is given the "hidden" class, it's other class(es) must be preserved, except for the "visible" class being replaced.
function hideSections() {
// Initialise array with div IDs
var divs = new Array("tab-1", "tab-2", "tab-3", "tab-4", "tab-5");
// Loop through divs in array
for (var count = 0; count < divs.length; count++) {
// Get existing classes
var div = document.getElementById(divs[count]);
var divClass = div.getAttribute("class");
// Remove "visible" class if it exists
divClass = divClass.replace("visible", "");
// Append "hidden" class
div.setAttribute("class", divClass + " hidden");
}
}
For some reason this function is not working, though it is definitely being called.
An alert() placed inside the loop appears, if placed before the line [[var divClass = div.getAttribute("class");]]. Placed after this line, it does not, so I'm guessing this line is where the problem is.
All the divs have a class attribute specified.
My guess is you have elements which don't have a class attribute so divClass is null - causing an error on line divClass = divClass.replace("visible", "");. (can't call a method off a null value)
Try checking for the attribute:
// Initialise array with div IDs
var divs = new Array("tab-1", "tab-2", "tab-3", "tab-4", "tab-5");
// Loop through divs in array
for (var count = 0; count < divs.length; count++) {
// Get existing classes
var div = document.getElementById(divs[count]);
var divClass = '';
if(divClass = div.getAttribute("class")) {
// Remove "visible" class if it exists
divClass = divClass.replace("visible", "");
}
// Append "hidden" class
div.setAttribute("class", divClass + " hidden");
}
... or you can check out the JSFiddle demo I created.
What you need are utility functions to add and remove classes. Here's some I use:
var trim = function(s) {
return s.replace(/(^\s+)|(\s+$)/g,'').replace(/\s+/g,' ');
}
var hasClassName = function(el, cName) {
if (typeof el == 'string') el = document.getElementById(el);
var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)');
return el && re.test(el.className);
}
var addClassName = function(el, cName) {
if (typeof el == 'string') el = document.getElementById(el);
if (!hasClassName(el, cName)) {
el.className = trim(el.className + ' ' + cName);
}
}
var removeClassName = function(el, cName) {
if (typeof el == 'string') el = document.getElementById(el);
if (hasClassName(el, cName)) {
var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)','g');
el.className = trim(el.className.replace(re, ''));
}
}
Now you can do:
addClass(elementOrId, 'classValue');
Wrap in a "namespace" or whatever suits.
Try something like this:
function hideSections() {
// Initialise array with div IDs
var divs = ["tab-1", "tab-2", "tab-3", "tab-4", "tab-5"];
// Loop through divs in array
for (var count = 0; count < divs.length; count++) {
// Get existing classes
var div = document.getElementById(divs[count]);
var divClass = div.getAttribute("class");
// Remove "visible" class if it exists
var regex = new RegExp( '(?:^|\\s+)' + 'visible' + '(?=\\s|$)', 'i' );
if ( regex.test( divClass ) ) {
divClass = divClass.replace( regex, '' ).replace( /^\s+/, '' );
// Append "hidden" class
if ( divClass )
div.setAttribute( 'class', divClass + ' hidden' );
else
div.setAttribute( 'class', 'hidden' );
}
}
}
Also you can try this out from jsfiddle