A little background of my problem:
I'm making a board-based game when the user is going to be able to make a path from a square to another one, the thing is that when a square is clicked it should stay highlighted no matter if pointer is over of it and then leaves it. It seems when the square is clicked and then the pointer leaves it the handlerIn of .hover() changes the state of the square's path-type attribute making possible to the square to be unhighlited when the pointer enter and leaves the square.
this is what I've got so far:
$(function() {
$('td.soccer-field').click(function(){
if ($('#dice1').text() != '' && $('#dice2').text() != '') {
if ($("[path-type='begin-path']").length == 0) {
$(this).attr('path-type','begin-path');
} else if ($("[path-type='begin-path']").length && $(this).attr('path-type') != 'end-path'){
$(this).attr('path-type','end-path');
$('[path-type="selecting-actual-path"]').attr('path-type','actual-path');
} else if ($(this).attr('path-type') == 'end-path'){
$(this).attr('path-type','');
};
}
});
$('td.soccer-field').hover(
function () {
if ($('#dice1').text() != '' && $('#dice2').text() != '') {
if ($("[path-type='begin-path']").length == 0) {
$(this).attr('path-type','select-begin-path');
} else if ($(this).attr('path-type') == ''){
var actualCell = $(this).attr('id') + $(this).parent().attr('id');
var cell, distance,dicesResult = parseInt($('#dice1').text())+ parseInt($('#dice2').text());
$("[path-type*='path']").each(function () {
cell = $(this).attr('id') + $(this).parent().attr('id');
distance = new Board().calculateDistanceSquares(actualCell,cell);
if (distance == 1 && $("[path-type='selecting-actual-path']").length < (dicesResult -2))
{
$(this).attr('path-type','selecting-actual-path');
return false;
}
});
}
};
},function () {
if ($(this).attr('path-type') == 'selecting-actual-path' || $(this).attr('path-type') == 'select-begin-path') {
$(this).attr('path-type','');
}
});
$('#diceRoller').click(function() {
$('#dice1').text(Math.floor(Math.random()*6)+1);
$('#dice2').text(Math.floor(Math.random()*6)+1);
$(this).attr('disabled',true);
});
});
//function Board(playerTurn, piecesPosition, gamePhase, gameBegginingType, container)
function Board(){
this.buildBoard = function (container) {
var board = $('<table></table>').attr('id','board');
var row, cell,containerHeight,containerWidth;
for (var i=0; i<10; i++){
row = $('<tr></tr>').attr('id',i+1);
for (var j=0; j<20; j++){
cell = $('<td></td>');
cell.attr('path-type','');
if ((j == 0 || j == 19) && (i >= 3) && (i <= 6)) {
cell.addClass('behind-goal');
}
else if ((j > 0) && (j < 19)){
cell.attr('id',String.fromCharCode(j+96));
cell.addClass("soccer-field");
};
row.append(cell);
}
board.append(row);
}
$('#'+container).append(board);
};
this.calculateHorizontalDistance = function (sq1,sq2) {
var column1 = sq1.substring(0,1).charCodeAt(0);
var column2 = sq2.substring(0,1).charCodeAt(0);
return ( Math.abs(column1-column2) );
};
this.calculateVerticalDistance = function (sq1, sq2) {
var row1 = parseInt(sq1.substring(1));
var row2 = parseInt(sq1.substring(1));
return ( Math.abs(row1-row2) );
};
this.calculateDistanceSquares = function(sq1, sq2){
return(this.calculateVerticalDistance(sq1,sq2)+this.calculateHorizontalDistance(sq1,sq2));
}
}
var board = new Board();
board.buildBoard('left');
#left table{
width: 60em;
height: 25em;
border:0.2em solid black;
border-collapse:collapse;
}
#left table tr{
height: 2.5em;
}
#left table tr td{
width: 3.33em;
}
td.soccer-field{
border: 0.1em solid black;
}
td.behind-goal{
background-color: #F8FAB4;
}
td[path-type*="path"]{
border: 0.15em solid #F8FAB4;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="boardContainer">
<div id="right">
<p id="dice1"></p><p id="dice2"></p>
<button id="diceRoller">Lanzar Dados</button>
</div>
<div id="left"></div>
</div>
A little help will be really appreciate
To prevent that you can add an attribute on the element whenever it is clicked and remove it later on second click. Now in the hover handler check for this attribute on the element, if it is present(or set) then don't do anything just return from the handler.
Something like this
$('td.soccer-field').click(function(){
$(this).data('clicked', !!$(this).data('clicked'));
...
...
});
$('td.soccer-field').hover(
function () {
if ($(this).data('clicked')) return;
...
...
},
function () {
if ($(this).data('clicked')) return;
...
...
});
Related
I am using the following jQuery script from enter link description here
<script>
var calendarObjects = [
{name:"Event Type 1", colour:"#735f9e"},
{name:"Event Type 2", colour:"#0000FF"},
{name:"Event Type 3", colour:"#0066cc"},
{name:"Event Type 4", colour:"#83b53f"},
{name:"Event Type 5", colour:"#ff99cc"} ,
]
</script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript">
LoadSodByKey("SP.UI.ApplicationPages.Calendar.js", function () {
WaitForCalendarToLoad();
});
var SEPARATOR = "|||";
function WaitForCalendarToLoad() {
var _renderGrids = SP.UI.ApplicationPages.SummaryCalendarView.prototype.renderGrids;
SP.UI.ApplicationPages.SummaryCalendarView.prototype.renderGrids = function($p0) {
_renderGrids.call(this, $p0);
ColourCalendar();
}
var _onItemsSucceed = SP.UI.ApplicationPages.CalendarStateHandler.prototype.onItemsSucceed;
SP.UI.ApplicationPages.CalendarStateHandler.prototype.onItemsSucceed = function($p0, $p1) {
_onItemsSucceed.call(this, $p0, $p1);
ColourCalendar();
}
}
function ColourCalendar() {
// Find calendar links (i.e. links that contain the separator |||)
if ($('a:contains(' + SEPARATOR + ')') != null) {
// Loop through calendar links
$('a:contains(' + SEPARATOR + ')').each(function (i) {
// Get the div of the calendar entry
$box = $(this).parents('div[title]');
// Get the category, colour and actual text
var category = GetCategory(this.innerHTML);
if (category != "")
{
var colour = GetColourCodeFromName(category);
var actualText = GetActualText(this.innerHTML);
// Set html of calendar entry
this.innerHTML = actualText;
// Set the title of the div
$($box).attr("title", GetActualText($($box).attr("title")));
// Set class of div to category without spaces
$($box).attr("class", "calendarEvent " + category.replace(/ /g, ""));
// Set the background colour
$box.css('background-color', '#da7b2f');
}
else
{
// Set html of calendar entry
this.innerHTML = GetActualText(this.innerHTML);
// Set class of div to category without spaces
$($box).attr("class", "calendarEvent");
// Set the background colour
$box.css('background-color', '#da7b2f');
}
});
}
// Setup filter links
SetupFilterLinks();
// If filter already selected
var selectedFilter = document.getElementById('hfdSelectedFilter').value;
if (selectedFilter != "") {
FilterCategory(document.getElementById('hfdSelectedFilter').value);
}
}
function GetActualText(originalText) {
var parts = originalText.split(SEPARATOR);
return parts[0] + parts[2];
}
function GetCategory(originalText) {
var parts = originalText.split(SEPARATOR);
return parts[1];
}
function GetColourCodeFromName(name) {
// Iterate calendar objects
for (var i = 0, len = calendarObjects.length; i < len; i++) {
if (calendarObjects[i].name === name)
return calendarObjects[i].colour; // Return as soon as the object is found
}
return "#999999"; // Default to dark grey
}
function FilterCategory(category) {
// Get category with no spaces
var categoryNoSpaces = category.replace(/ /g, "");
// If divs with class "calendarEvent" exist
if ($('div.calendarEvent') != null) {
// Loop through divs
$('div.calendarEvent').each(function (i) {
// Hide divs
this.style.display = "none";
});
}
// If div(s) with category class exist
if ($('div.' + categoryNoSpaces) != null) {
// Loop through divs
$('div.' + categoryNoSpaces).each(function (i) {
// Set display to block
this.style.display = "block";
});
}
// Set hidden field value
document.getElementById('hfdSelectedFilter').value = categoryNoSpaces;
// Expand all days
expandCalCheck();
// Hide collapse links
hideCollapseLinks();
}
function expandCalCheck() {
var a = $("a.ms-cal-nav", $("div.ms-acal-rootdiv:last>div")).get(0);
if (a) {
for (var r = 0; r < 6; r++) {
var a = $("a.ms-cal-nav", $("div.ms-acal-rootdiv:last>div").get(r)).get(0);
if (a)
if (a.innerText.indexOf("more") >= 0) {
a.click();
}
}
}
}
function hideCollapseLinks() {
if ($('a:contains(collapse)') != null) {
// Loop through collapse links
$('a:contains(collapse)').each(function (i) {
this.style.display = "none";
});
}
}
function ShowAllEvents() {
// If divs with class "calendarEvent" exist
if ($('div.calendarEvent') != null) {
// Loop through divs
$('div.calendarEvent').each(function (i) {
// Hide divs
this.style.display = "block";
});
// Set hidden field value
document.getElementById('hfdSelectedFilter').value = "";
}
}
function SetupFilterLinks()
{
// Variables
var filters = [];
// Loop through calendar objects
$(calendarObjects).each(function (i) {
var name = this.name;
var colour = GetColourCodeFromName(name);
// Add filters variable
filters.push("<a href='javascript:void(0)' id='" + name.replace(/ /g, "") + "' class='filterLink' style='background-color:" + colour + "' onclick='FilterCategory(\"" + name + "\")'>" + name + "</a> ");
});
// Add filters to page
$('.calendarFilters').replaceWith(filters.join(''));
$('.filters a').click(function () {
$(this).addClass('selected');
$(this).siblings().removeClass('selected');
});
}
</script>
<style>
.filters
{
margin:10px 0 0 0;
}
.filters .title
{
font-size:15px;
margin:0 5px 0 0;
}
.filters .filterLink
{
color:#ffffff !important;
padding:3px 6px 4px 6px;
display: inline-block;
margin-bottom: 5px;
}
.filters .filterLinkShowAll
{
color:#ffffff !important;
background:#666666;
}
.filters .selected
{
border:2px solid #000000 !important;
padding:1px 4px 2px 4px;
}
</style>
<input type="hidden" id="hfdSelectedFilter" name="hfdSelectedFilter">
<div class="filters">
<span class="title">Filters:</span>
Show all
<div class="calendarFilters">
<!-- -->
</div>
</div>
There is a variable that controls color
$box.css('background-color', '#da7b2f');
The problem is when I try to remove the background-color variable, it does not use the following stylesheet and just inherits the color from the table it's from. How can I incorporate this stylesheet so it works with the jQuery script?
<style>
.ms-acal-time, .ms-acal-apanel-color {
DISPLAY: none;
}
.ms-acal-color6{
background-color:#0066cc!important;
}
.ms-acal-apanel-color6{
background-color:#0066cc!important;
}
.ms-acal-color8{
background-color:#787878!important;
}
.ms-acal-apanel-color8{
background-color:#787878!important;
}
</style>
Hi,
I'm learning/practicing to make my custom slider in JS/JQuery, and I've written below code. Its almost running well but little issues. What I'm doing is I'm running it two types,
Auto running after each 5 seconds with autoRun() Function
On every click to slider indicator run to relevant slide with click event.
In below code, I'm facing couple of issues, and will be very thankful to you if you help me.
Issues I'm facing are:
When I click to slider indicator, I want to disable auto Run function for a specific time like 5 second so my slider look more professional.
When it goes to last slide or come back to first slide, console is showing an error below, and it also take double time eg: 10 seconds to go next slide.
"Uncaught TypeError: Cannot read property 'left' of undefined"
$(function () {
var $mainSliderWrap = $('#slider_main_wrapper')
, $sliderMain = $mainSliderWrap.find('.main-slider')
, $sliderchildren = $sliderMain.children('li')
, $sliderIndicator = $mainSliderWrap.find('.slider-main-indicator');
// Slider Setup
window.addEventListener('resize', initMainSlider);
initMainSlider();
// Slider SetUp function
function initMainSlider() {
var wWidth = window.outerWidth
, sliderMainWidth = wWidth * $sliderchildren.length
$sliderMain.css('width', sliderMainWidth + 'px');
$sliderMain.children('li').first().addClass('visible');
$sliderIndicator.children('li').first().addClass('active');
}
// Want to Run Slider on Click event
$sliderIndicator.on('click', 'li', updateMainSlider);
// If Click Event Not happenening then I want to auto run Slider after 5 seconds
autoRun()
function autoRun() {
var mainSliderChildLenght = $sliderchildren.length;
var i = 0;
var next = true;
var dir;
setInterval(function () {
if (mainSliderChildLenght == i || i < 0) {
next = !next;
if (i < 0) {
i = 0;
}
}
if (next) {
dir = 'next';
i++;
}
else {
dir = 'prev';
i--;
if(i < 0) {
return
}
}
updateMainSlider(dir);
$('#result').text(i)
}, 5000);
}
// Here is the function for Updating the Slider
function updateMainSlider(a) {
var visibleSlide = $sliderchildren.filter('.visible')
, actualTranslate = getTranslateValue($sliderMain, 'X');
if (a == 'next' || a == 'prev') { // inside this if is running when function is called from autoRun()
console.log(a)
var newSlide = (a == 'next') ? visibleSlide.next() : visibleSlide.prev()
, newSlideOffsetLeft = newSlide.offset().left
, valueToTranslte = -newSlideOffsetLeft + actualTranslate;
setTranslateValue($sliderMain, 'translateX', valueToTranslte);
visibleSlide.removeClass('visible');
newSlide.addClass('visible');
$sliderIndicator.children('.active').removeClass('active');
$sliderIndicator.find('li').eq(newSlide.index()).addClass('active');
}
else { // inside this if is running when function is called from click event
console.log(a)
var newSlide = $(a.target)
, $newSlideIndicatorIndex = newSlide.index()
, $visibleSlideIndex = visibleSlide.index();
if ($newSlideIndicatorIndex !== $visibleSlideIndex && !$($sliderIndicator).hasClass('disable-click')) {
$($sliderIndicator).addClass('disable-click');
setTimeout(function () {
$($sliderIndicator).removeClass('disable-click');
}, 1000);
var diff = $newSlideIndicatorIndex - $visibleSlideIndex
, valueToTranslte = -(diff * window.outerWidth) + actualTranslate;
setTranslateValue($sliderMain, 'translateX', valueToTranslte);
$($sliderchildren[$visibleSlideIndex]).removeClass('visible');
$($sliderchildren[$newSlideIndicatorIndex]).addClass('visible');
$sliderIndicator.children('.active').removeClass('active');
$sliderIndicator.find('li').eq($newSlideIndicatorIndex).addClass('active');
} // end if
} // end else
} // end function
// SetTranslate Value Fucntion
function setTranslateValue(element, property, value) {
$(element).css({
'transform': property + '(' + value + 'px)'
});
}
// Get Translate Value function
function getTranslateValue(element, axis) {
var trValue = $(element).css('transform');
if (trValue !== 'none') {
trValue = trValue.split(')')[0];
trValue = trValue.split(',');
trValue = (axis == 'X') ? trValue[4] : trValue[5];
}
else {
trValue = 0;
}
return Number(trValue);
}
})
ol {
list-style: none;
margin: 0;
padding: 0;
}
body {
margin: 0;
padding: 0;
}
.slider-main-wrapper {
box-shadow: inset 0 0 20px orange;
min-height: 100vh;
}
ol.main-slider {
height: 85vh;
box-shadow: inset 0 0 20px green;
transition: transform 500ms ease;
}
ol.main-slider > li {
float: left;
}
ol.main-slider > li .silder-main-content {
width: 100vw;
height: 85vh;
display: flex;
justify-content: center;
align-items: center;
}
ol.main-slider > li.visible .silder-main-content {
box-shadow: inset 0 0 140px green;
}
ol.slider-main-indicator {
height: 15vh;
display: flex;
}
ol.slider-main-indicator li {
box-shadow: inset 0 0 2px green;
flex: 1;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
ol.slider-main-indicator li.active {
box-shadow: inset 0 0 80px green;
cursor: default;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result" style="font-size: 30px; position: absolute;
top: 0; left: 0"></div>
<div class="slider-main-wrapper" id="slider_main_wrapper">
<ol class="main-slider">
<li>
<div class="silder-main-content">
<h1>First Slide</h1>
</div>
</li>
<li>
<div class="silder-main-content">
<h2>Second Slide</h2>
</div>
</li>
<li>
<div class="silder-main-content">
<h1>Third Slide</h1>
</div>
</li>
<li>
<div class="silder-main-content">
<h1>Fourth Slide</h1>
</div>
</li>
</ol>
<!--end slides-->
<ol class="slider-main-indicator">
<li> <span class="text">First Slide</span> </li>
<li> <span class="text">Second Slide</span> </li>
<li> <span class="text">Third Slide</span> </li>
<li> <span class="text">Fourth Slide</span> </li>
</ol>
<!--end slide indicator-->
</div>
you'll want to clearInterval when you click, the setInterval again once the processing due to the "click" event completes - so, for a start, you'll need to save the returned value of setInterval to use in clearInterval
autoRun in this code returns a function which starts the interval
this is just "part" of your code, not the whole thing - trying to keep it readable regarding the changes I have implemented
$sliderIndicator.on('click', 'li', updateMainSlider);
// save the function returned by autoRun
var go = autoRun();
// start autoRun
go();
// add a variable to store interval identifier
var interval;
function autoRun() {
var mainSliderChildLenght = $sliderchildren.length;
var i = 0;
var next = true;
var dir;
// return a function to begin autoRun for real
return function() {
// save interval identifier
interval = setInterval(function () {
// your code unchanged
}, 5000);
};
}
function updateMainSlider(a) {
var visibleSlide = $sliderchildren.filter('.visible')
, actualTranslate = getTranslateValue($sliderMain, 'X');
if (a == 'next' || a == 'prev') {
// your code - unchanged
} else {
// clear interval
clearInterval(interval);
// your code - unchanged
// now add this to restart the interval
go();
}
}
You may still need to tweak some things, I haven't gone through your code in depth
as requested
$(function () {
var $mainSliderWrap = $('#slider_main_wrapper')
, $sliderMain = $mainSliderWrap.find('.main-slider')
, $sliderchildren = $sliderMain.children('li')
, $sliderIndicator = $mainSliderWrap.find('.slider-main-indicator');
// Slider Setup
window.addEventListener('resize', initMainSlider);
initMainSlider();
// Slider SetUp function
function initMainSlider() {
var wWidth = window.outerWidth
, sliderMainWidth = wWidth * $sliderchildren.length
$sliderMain.css('width', sliderMainWidth + 'px');
$sliderMain.children('li').first().addClass('visible');
$sliderIndicator.children('li').first().addClass('active');
}
// Want to Run Slider on Click event
$sliderIndicator.on('click', 'li', updateMainSlider);
// If Click Event Not happenening then I want to auto run Slider after 5 seconds
var go = autoRun();
// start autoRun
go();
var interval;
function autoRun() {
var mainSliderChildLenght = $sliderchildren.length;
var i = 0;
var next = true;
var dir;
return function() {
setInterval(function () {
if (mainSliderChildLenght == i || i < 0) {
next = !next;
if (i < 0) {
i = 0;
}
}
if (next) {
dir = 'next';
i++;
}
else {
dir = 'prev';
i--;
if(i < 0) {
return
}
}
updateMainSlider(dir);
$('#result').text(i)
}, 5000);
});
}
// Here is the function for Updating the Slider
function updateMainSlider(a) {
var visibleSlide = $sliderchildren.filter('.visible')
, actualTranslate = getTranslateValue($sliderMain, 'X');
if (a == 'next' || a == 'prev') { // inside this if is running when function is called from autoRun()
console.log(a)
var newSlide = (a == 'next') ? visibleSlide.next() : visibleSlide.prev()
, newSlideOffsetLeft = newSlide.offset().left
, valueToTranslte = -newSlideOffsetLeft + actualTranslate;
setTranslateValue($sliderMain, 'translateX', valueToTranslte);
visibleSlide.removeClass('visible');
newSlide.addClass('visible');
$sliderIndicator.children('.active').removeClass('active');
$sliderIndicator.find('li').eq(newSlide.index()).addClass('active');
}
else { // inside this if is running when function is called from click event
clearInterval(interval);
console.log(a)
var newSlide = $(a.target)
, $newSlideIndicatorIndex = newSlide.index()
, $visibleSlideIndex = visibleSlide.index();
if ($newSlideIndicatorIndex !== $visibleSlideIndex && !$($sliderIndicator).hasClass('disable-click')) {
$($sliderIndicator).addClass('disable-click');
setTimeout(function () {
$($sliderIndicator).removeClass('disable-click');
}, 1000);
var diff = $newSlideIndicatorIndex - $visibleSlideIndex
, valueToTranslte = -(diff * window.outerWidth) + actualTranslate;
setTranslateValue($sliderMain, 'translateX', valueToTranslte);
$($sliderchildren[$visibleSlideIndex]).removeClass('visible');
$($sliderchildren[$newSlideIndicatorIndex]).addClass('visible');
$sliderIndicator.children('.active').removeClass('active');
$sliderIndicator.find('li').eq($newSlideIndicatorIndex).addClass('active');
} // end if
go();
} // end else
} // end function
// SetTranslate Value Fucntion
function setTranslateValue(element, property, value) {
$(element).css({
'transform': property + '(' + value + 'px)'
});
}
// Get Translate Value function
function getTranslateValue(element, axis) {
var trValue = $(element).css('transform');
if (trValue !== 'none') {
trValue = trValue.split(')')[0];
trValue = trValue.split(',');
trValue = (axis == 'X') ? trValue[4] : trValue[5];
}
else {
trValue = 0;
}
return Number(trValue);
}
})
I'm trying to learn Javascript and at the moment and I am working on AddEventListener.
What I'm trying to do is to add a new row and so far it works.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style>
.colorOrange {
background-color: orange;
}
.colorBlue {
background-color: blue;
}
.colorYellow {
background-color: yellow;
}
.colorGray {
background-color: gray;
}
.colorRed {
background-color: red;
}
.colorGreen {
background-color: green;
}
.colorWhite {
background-color: white;
}
#main {
margin: 0 auto;
width: 325px;
text-align: center;
background-color: gray;
}
.row {
width: 300px;
padding: 10px;
border: 1px solid black;
display: block;
}
.hideButton, .mainText, .deleteButton {
margin: 0 auto;
padding: 10px;
border: 1px solid black;
display: inline;
}
.btn {
}
</style>
</head>
<body>
<div id="main">
<div class="AddBtn btn">Add</div>
<input type="text" id="txtBox" name="text till ruta" />
</div>
<script>
var rownr = 0;
function addListeners() {
var addButton = document.getElementsByClassName('AddBtn');
for (var i = 0; i < addButton.length; i++) {
var addBtn = addButton[i];
addBtn.addEventListener('click', function () {
var elBtn = event.srcElement;
var valueBtn = elBtn.textContent;
alert(valueBtn);
hideOrShow();
addRow();
function addRow() {
switch (valueBtn) {
case "Add":
var input = document.getElementById('txtBox').value;
rownr++;
var div = document.createElement('div');
div.className = "row";
document.getElementById("main").appendChild(div);
var div2 = document.createElement('div');
div2.className = "hideButton colorGreen";
var tx = document.createTextNode("<");
div2.appendChild(tx);
div2.addEventListener('click', hideOrShow, false);
div.appendChild(div2);
var div3 = document.createElement("div");
if (input.toLowerCase() == "red") {
div3.className = "mainText colorRed";
}
else if (input.toLowerCase() == "orange") {
div3.className = "mainText colorOrange";
}
else if (input.toLowerCase() == "blue") {
div3.className = "mainText colorBlue";
}
else if (input.toLowerCase() == "yellow") {
div3.className = "mainText colorYellow";
}
else if (input.toLowerCase() == "gray") {
div3.className = "mainText colorGray";
} else {
div3.className = "mainText colorWhite";
}
tx = document.createTextNode(rownr + " " + input);
div3.appendChild(tx);
div.appendChild(div3);
var div4 = document.createElement("div");
div4.className = "deleteButton colorRed";
tx = document.createTextNode("X");
div4.appendChild(tx);
//div4.addEventListener('click', deleBtn, false);
div.appendChild(div4);
var linebreak = document.createElement("br");
div.appendChild(linebreak);
default:
}
}
So far everything works as I want it to do. But when I click on "<" it will go in to this function and find all tags with the hideButton class in it.
The first click it won't find anything, but the second time it will find the "<" value and an alert window will popup and show the value. Here is where I
get lost and can't get it to work. When you click the the third time it will
loop or whatever to call it - anyway it will show the alert window 2 times and
then if you repeat the same click it will do the same thing 3 times and so it goes.
function hideOrShow() {
var hideButton = document.getElementsByClassName('hideButton');
for (var j = 0; j < hideButton.length; j++) {
hideBtn = hideButton[j];
hideBtn.addEventListener('click', function () {
var hideElBtn = event.srcElement;
var valueHideBtn = hideElBtn.textContent;
alert(valueHideBtn);
}, false);
}
}
}, false);
}
}
window.onload = addListeners;
</script>
</body>
</html>
The goal with this exercise is that
when you click add button add the text from the input field and add that text to the new row.
and "<" shall hide the row and change it to ">" to show it again
and "X" shall just delete the row.
But what I need help with is finding the value part that I mentioned above.
Here is my rework of your javascript. I explained my solution in your comment, but it may be a bit more clear if illustrated.
In the addListeners function, I removed the hideOrShow call as it shouldn't be called in the add button.
Next, I removed the for loop in the hideOrShow method as you really are only after the caller. I also removed the addEventListener call in the same method as you already have an event listener on that element, so there's no need to add one again.
var rownr = 0;
function addListeners() {
var addButton = document.getElementsByClassName('AddBtn');
for (var i = 0; i < addButton.length; i++) {
var addBtn = addButton[i];
addBtn.addEventListener('click', function () {
var elBtn = event.srcElement;
var valueBtn = elBtn.textContent;
alert(valueBtn);
//hideOrShow();
addRow();
function addRow() {
switch (valueBtn) {
case "Add":
var input = document.getElementById('txtBox').value;
rownr++;
var div = document.createElement('div');
div.className = "row";
document.getElementById("main").appendChild(div);
var div2 = document.createElement('div');
div2.className = "hideButton colorGreen";
var tx = document.createTextNode("<");
div2.appendChild(tx);
div2.addEventListener('click', hideOrShow, false);
div.appendChild(div2);
var div3 = document.createElement("div");
if (input.toLowerCase() == "red") {
div3.className = "mainText colorRed";
}
else if (input.toLowerCase() == "orange") {
div3.className = "mainText colorOrange";
}
else if (input.toLowerCase() == "blue") {
div3.className = "mainText colorBlue";
}
else if (input.toLowerCase() == "yellow") {
div3.className = "mainText colorYellow";
}
else if (input.toLowerCase() == "gray") {
div3.className = "mainText colorGray";
} else {
div3.className = "mainText colorWhite";
}
tx = document.createTextNode(rownr + " " + input);
div3.appendChild(tx);
div.appendChild(div3);
var div4 = document.createElement("div");
div4.className = "deleteButton colorRed";
tx = document.createTextNode("X");
div4.appendChild(tx);
//div4.addEventListener('click', deleBtn, false);
div.appendChild(div4);
var linebreak = document.createElement("br");
div.appendChild(linebreak);
default:
}
}
function hideOrShow() {
var hideButton = document.getElementsByClassName('hideButton');
var hideElBtn = event.srcElement;
var valueHideBtn = hideElBtn.textContent;
alert(valueHideBtn);
}
}, false);
}
}
window.onload = addListeners;
I used a resizing function in my table and its working fine. The problem is its working in the td's of the first row only. For other td's, its not working.
I tried of changing the width of the tr of the selected td and also tried of changing the table width also, but its not working. I dont know what is the problem with that.
The width for the corresponding td is calculated correctly while dragging, but its not applied on the td. But its working fine in the td's of the first row.
var ob;
var obLeft;
var obRight;
var over = false;
var iEdgeThreshold = 10;
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft;
curtop = obj.offsetTop;
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
}
}
return [curleft, curtop];
}
/* Function that tells me if on the border or not */
function isOnBorderRight(objTable, objTh, event) {
var width = objTh.offsetWidth;
var left = objTh.offsetLeft;
var pos = findPos(objTable);
var absRight = pos[0] + left + width;
if (event.clientX > (absRight - iEdgeThreshold)) {
return true;
}
return false;
}
function getNodeName(objReference, nodeName) {
var oElement = objReference;
while (oElement != null && oElement.tagName != null) {
if (oElement.tagName == nodeName) {
return oElement;
}
oElement = oElement.parentNode;
}
return null;
}
function doResize(objTh, event) {
if (!event) event = window.event;
var objTable = getNodeName(objTh, "TABLE");
if (isOnBorderRight(objTable, objTh, event)) {
over = true;
objTh.style.cursor = "e-resize";
} else {
over = false;
objTh.style.cursor = "";
}
return over;
}
function doneResizing() {
over = false;
}
function MD(event) {//alert(event.srcElement.tagName+ " and "+event.target.tagName)
if (!event) event = window.event;
MOUSTSTART_X = event.clientX;
MOUSTSTART_Y = event.clientY;
if (over) {
if (event.srcElement) ob = event.srcElement;
else if (event.target) ob = event.target;
else return;
ob = getNodeName(ob, "TD");
if (ob == null) {return;
}
//ob2 = getNodeName(ob,"TABLE");
//obLeft = ob.previousSibling;
obRight = ob.nextSibling;
//obLeft = ob.previousElementSibling;
//obRight = ob.nextElementSibling; // Uncomment For FF
obwidth = parseInt(ob.style.width);
if (obLeft != null)
obLeftWidth = parseInt(obLeft.style.width);
if (obRight != null)
obRightWidth = parseInt(obRight.style.width);
//obwidth2=parseInt(ob2.offsetWidth);
alert(obRight+" and "+obwidth+" and "+obRightWidth);
}
}
function MM(event) {
if (!event) event = window.event;
if (ob) {
st = event.clientX - MOUSTSTART_X + obwidth;
//st2=event.clientX-MOUSTSTART_X+obwidth2;
document.getElementById("infoDiv").innerHTML = "st=" + st + " clientX=" + event.clientX + " moustart_x=" + MOUSTSTART_X + " obwidth=" + obwidth;
//document.getElementById("infoDiv").innerHTML += ;
//document.getElementById("infoDiv").innerHTML += ;
//document.getElementById("infoDiv").innerHTML += obwidth;
if (st >= 10) {
ob.style.width = st;
//ob2.style.width=st2;
//obLeft.style.width=st-obLeftWidth;
obRight.style.width = (parseInt(obwidth - st + obRightWidth) > 10 ? (obwidth - st + obRightWidth) : iEdgeThreshold + "px");
}
if (document.selection) document.selection.empty();
else if (window.getSelection) window.getSelection().removeAllRanges();
}
}
function MU(event) {
if (!event) event = window.event;
if (ob) {
if (document.selection) document.selection.empty();
else if (window.getSelection) window.getSelection().removeAllRanges();
ob = null;
}
}
document.onmousedown = MD;
document.onmousemove = MM;
document.onmouseup = MU;
html>body div.scrollable tbody {
overflow: auto;
}
table.resizable th{
text-align:center;
overflow: hidden;
}
/* if mozilla, add 10 for the scrollbar */
html>body th.scrollbarCol {
width:10px;
}
table.resizable td{
overflow: hidden;
}
table.resizable{
table-layout:fixed;
}
table.resizable input{
width:100%;
}
table.resizable textarea{
width:100%;
}
.nowrap {
white-space:nowrap;
}
/* needed for IE */
table.tabular th.scrollbarCol {
background-color:transparent;
}
table.tabular {
FONT-SIZE: 13px;
FONT-FAMILY: 'Verdana, Arial, Helvetica, sans-serif';
COLOR: #336699;
}
table.tabular thead {
COLOR: #ffffff;
FONT-WEIGHT: bold;
}
table.tabular th{
background-color:#c0c0c0;
padding: 4px;
}
table.tabular td {
background-color:#EAF4F3;
padding: 2px;
}
<div class="scrollable">
<TABLE id="mytable" style="width:100%; table-layout:fixed" class="sortable resizable tabular">
<THEAD>
<TR>
<td onmousemove="doResize(this,event)" onmouseover="doResize(this,event)" onmouseout='doneResizing()' style='width:60px'>Index</td>
<td onmousemove="doResize(this,event)" onmouseover="doResize(this,event)" onmouseout='doneResizing()' style='width:170px'><span class="nowrap">Parameter Name</span></td>
<td onmousemove="doResize(this,event)" onmouseover="doResize(this,event)" onmouseout='doneResizing()' style='width:170px'><span class="nowrap">Parameter Value</span></td>
<td onmousemove="doResize(this,event)" onmouseover="doResize(this,event)" onmouseout='doneResizing()' style='width:110px'><span class="nowrap">Page Name</span></td>
</TR>
</THEAD>
<TBODY style="height:200px">
<TR>
<Td>0</Td>
<Td>1_2</Td>
<Td>234</Td>
<Td>1_3</Td>
</TR>
</TBODY>
</table>
</div>
<span id="infoDiv"></span>
I think the problem is that when you pass 'this' in the second level of td's you're not traversing back up the dom enough to get to the thead td. I would try putting some id's to your first td elements so you can directly pass them to your function from your second tds.
EDIT:
I think this code is the issue:
function getNodeName(objReference, nodeName) {
var oElement = objReference;
while (oElement != null && oElement.tagName != null) {
if (oElement.tagName == nodeName) {
return oElement;
}
oElement = oElement.parentNode;
}
return null;
}
When you call it from MD, you call like this:
ob = getNodeName(ob, "TD");
So when you enter getNodeName() and it gets to the if (oElement.tagName == nodeName) statement, it's eval to true and then exits the function. Then, when you do obRight = ob.nextsibling, it isn't working on the top-level td element like you want, it's working only on the bottom one. And I don't think you can set widths of those elements outside the tr in thead.
What I think you need is another check either in getNodeName() or MD() functions that identifies where you are in the DOM so you can get back to the top of the table, which is where you want to be to change the widths.
I would like to know how can I define a bigger variable for a set of variables that I have in javascript: showFootnotesPanel();, showReferencesPanel();, showImagesPanel();, showInformationPanel();.
Would it be something like this?
function showPanel() {
var x = [showFootnotesPanel();showReferencesPanel();showImagesPanel();showInformationPanel();]
}
Update:
I have this function that used to open a side panel on the right side and color the content:
var els = document.getElementsByClassName('change-color'),
target = document.getElementsByClassName('resources'),
changeColor = function(a) {
elements = document.getElementsByClassName("note");
for (var i = 0; i < elements.length; i++) {
console.log(elements[i])
elements[i].style.backgroundColor = "";
}
target = a.getAttribute('href');
element = document.querySelector('[data-id="' + target.substring(1, target.length) + '"]');
element.style.backgroundColor = a.getAttribute('data-color');
};
for (var i = els.length - 1; i >= 0; --i) {
els[i].onclick = function() {
showFootnotesPanel();
changeColor(this);
}
Now I have 4 side panels that need to respond to the same script, and I thought that by defining something like showPanel() is showFootnotesPanel() or showReferencesPanel() or showImagesPanel() or showInformationPanel() I might simplify things, so the last line of the script would be this instead just:
els[i].onclick = function(){showPanel();changeColor(this);}
Update 2:
Or is it possible to do this with the logical operator OR?
els[i].onclick = function(){showFootnotesPanel(); || showReferencesPanel(); || showImagesPanel(); || showInformationPanel();changeColor(this);}
Update 3:
This is the new script that I am using to hide and show the panels:
function showPanel(myPanel) {
var elem = document.getElementById(myPanel);
if (elem.classList) {
console.log("classList supported");
elem.classList.toggle("show");
} else {
var classes = elem.className;
if (classes.indexOf("show") >= 0) {
elem.className = classes.replace("show", "");
} else {
elem.className = classes + " show";
}
console.log(elem.className);
}
}
function hideOthers(one, two, three, four) {
if (one > "") {
var elem1 = document.getElementById(one);
var classes = elem1.className;
elem1.className = classes.replace("show", "");
}
if (two > "") {
var elem2 = document.getElementById(two);
var classes = elem2.className;
elem2.className = classes.replace("show", "");
}
if (three > "") {
var elem3 = document.getElementById(three);
var classes = elem3.className;
elem3.className = classes.replace("show", "");
}
if (four > "") {
var elem4 = document.getElementById(four);
var classes = elem4.className;
elem4.className = classes.replace("show", "");
}
return;
}
And this is the script that calls the panels and highlights the text on them:
var els = document.getElementsByClassName('change-color'),
target = document.getElementsByClassName('resources'),
changeColor = function(a) {
elements = document.getElementsByClassName("note");
for (var i = 0; i < elements.length; i++) {
console.log(elements[i])
elements[i].style.backgroundColor = "";
}
target = a.getAttribute('href');
element = document.querySelector('[data-id="' + target.substring(1, target.length) + '"]');
element.style.backgroundColor = a.getAttribute('data-color');
};
for (var i = els.length - 1; i >= 0; --i) {
els[i].onclick = function() {
hideOthers('footnotes-section', 'references-section', 'images-section', 'information-section');
showPanel('references-section');
changeColor(this);
}
}
Thank you!
Updated with a final solution.
In javascript you can declare variables by this way:
var text = ""; // String variable.
var number = 0; //Numeric variable.
var boolValue = true; //Boolean variable.
var arrayValue = []; // Array variable. This array can contain objects {}.
var obj = {}; // Object variable.
Check this version of your code.
// var text = ""; => String variable.
// var number = 0; => Numeric variable.
// var boolValue = true; => Boolean variable.
// var arrayValue = []; => Array variable. This array can contain objects {}.
// var obj = {}; => Object variable.
// This section of code is only to explain the first question.
(function() {
function showFootnotesPanel() {
return 10; // Random value.
}
function showReferencesPanel() {
return 30; // Random value.
}
function showImagesPanel() {
return 50; // Random value.
}
function showInformationPanel() {
return 90; // Random value.
}
function showPanel() {
return [
showFootnotesPanel(), // Index = 0
showReferencesPanel(), // Index = 1
showImagesPanel(), // Index = 2
showInformationPanel() // Index = 3
];
}
var bigVariable = showPanel(); // bigVariable is array of numeric values.
// Using logical operator to check status of variable about this demo code.
if (bigVariable[0] === 10 || bigVariable[1] === 30) {
console.log("Hey, with these values can show the FootnotesPanel and ReferencesPanel.");
} else {
console.log("With the current values can't show anything...");
}
console.log(bigVariable);
})();
// https://jsfiddle.net/dannyjhonston/t5e8g22b/
// This section of code attempts to answer the question of this post.
(function() {
// This function can be executed when the page is loaded.
function showPanel(panels) {
var panel, panelVisible = "";
var selPanels = document.getElementById("selPanels");
// In panels array...
for (var i = 0; i < panels.length; i++) {
// panels[0] = "ReferencesPanel";
panel = document.getElementById(panels[i]); // Get in the DOM tag context of the panel to set in the variable "panel".
panelVisible = panel.getAttribute("data-visible"); // HTML5 data attribute.
if (panelVisible == "true") {
panel.setAttribute("class", "show");
} else {
panel.setAttribute("class", "hide");
}
}
}
// This function is for set panel visibilty.
function setPanel(panelId, status) {
panel = document.getElementById(panelId);
panel.setAttribute("data-visible", status);
// Calling the showPanel function to check in the DOM.
showPanel(["ReferencesPanel", "InformationPanel", "ImagesPanel", "FootnotesPanel"]);
}
// Binding the change event to the select tag.
selPanels.addEventListener("change", function() {
// Executes setPanel function with panelId and true to update the data-visible attribute in the DOM.
setPanel(this.options[this.selectedIndex].value, "true");
});
// Executes showPanel function with array argument with panels Id. You need to specify every panel that want to handle.
showPanel(["ReferencesPanel", "InformationPanel", "ImagesPanel", "FootnotesPanel"]);
})();
#global {
border: solid 1px #6291AD;
}
.tools {
background-image: linear-gradient(#FFFFFF, #8999CE);
}
#global div[data-visible] {
height: 80px;
padding: 5px 0;
}
#global div p {
padding: 10px;
}
#ReferencesPanel {
background-image: linear-gradient(#FFFFFF, #FD9A9A);
float: left;
width: 20%;
}
#InformationPanel {
background-image: linear-gradient(#FFFFFF, #A1C7F1);
float: left;
width: 80%;
}
#ImagesPanel {
background-image: linear-gradient(#C6E9FB, #FFF);
width: 100%;
}
#FootnotesPanel {
background-image: linear-gradient(#C6E999, #FFF);
width: 100%;
}
.clear {
clear: both;
}
.show {
display: block;
}
.hide {
display: none;
}
<div id="global">
<div class="tools">Show Panel:
<br />
<!-- Demo -->
<select id="selPanels">
<option value="">[SELECT]</option>
<option value="ReferencesPanel">ReferencesPanel</option>
<option value="InformationPanel">InformationPanel</option>
<option value="ImagesPanel">ImagesPanel</option>
<option value="FootnotesPanel">FootnotesPanel</option>
</select>
</div>
<!-- You need to set data-visible attribute with true or false to show or hide a panel. -->
<div id="ReferencesPanel" data-visible="false">
<p>References Panel</p>
</div>
<div id="InformationPanel" data-visible="false">
<p>Information Panel</p>
</div>
<div class="clear"></div>
<div id="ImagesPanel" data-visible="false">
<p>Images Panel</p>
</div>
<div id="FootnotesPanel" data-visible="false">
<p>Foot notes Panel</p>
</div>
</div>
I dont understand your question exactly, but if you want to define a variable that contains other variables then you can use an object.
e.g:
var footNotesPanel = true;
var referencesPanel = true;
var imagesPanel = true;
var showPanels = {
footNotesPanel: footNotesPanel,
referencesPanel: referencesPanel,
imagesPanel: imagesPanel
}
/*
Option 2 - for showing/hiding side panels
1 ) create all your panels as they would appear, with all the data, but hide them with display:none;
2 ) call show panel function to show a panel.
*/
var showPanel(panel_id) {
var panel_element = $("#" + panel_id); /*panel that you want to show ( is hidden atm but somewhere on the page */
if (!panel_element.length) {
return false; //no panel with this id currently on page
} else {
//check the panel id and do some custom editing if needed, eg.
if (panel_id == "main_side_panel") {
//add some additional classes to body element etc
}
panel_element.show();
//Or Another option that you probably are looking for is below
if (panel_id == "footnotes_panel") {
showFootnotesPanel();
} else if (panel_id == "images_panel") {
showImagesPanel();
}
}
}
// And use it like this:
<div id="footnotes_panel" onclick="showPanel('footnotes_panel')"></div>
// Or simply get the element id from `event.target` and use `showPanel()` without arguments.