javascript toggle needs to stay - javascript

hi guys i need some help with javascript,
i have a toggle function for my text, waht you can see on www.jasperscheper.nl
but i want to make the text stay when you double click on over mij and home.
this is my code:
var bannerText1 = document.getElementById('bannertext1');
var bannerText2 = document.getElementById('bannertext2');
var displayedBannerText = 1;
function toggleBannerText() {
if(displayedBannerText == 1) {
// Switch to bannertext 2
bannerText1.className += ' hidebannertext';
displayedBannerText = 2;
bannertext2.className = 'welkom';
} else {
bannertext2.className += ' hidebannertext';
displayedBannerText = 1;
bannerText1.className = 'welkom';
}
}
<li class="knop" >
<button class="button" href="#"onclick="toggleBannerText()"> <h3>Home</h3></button>
</li>
<li class="knop">
<button class="button" onclick="toggleBannerText()" href="#"><h3>Over mij</h3></button>
</li>
thanks in advance,
Jasper Scheper.

Problem: You are calling the function toggleBannerText() every time there is a click on any of the buttons, There is no where the button's click events are distinguished, So every click assumes you need to show other text than the one shown.
Solution: Change your HTML to pass a parameter into the function saying which section it wants to show. Eg: toggleBannerText('Home')
<li class="knop" >
<button class="button" href="#"onclick="toggleBannerText('Home')"> <h3>Home</h3></button>
</li>
<li class="knop">
<button class="button" onclick="toggleBannerText('Over')" href="#"><h3>Over mij</h3>
</button> <!-- There was a typo you had a </a> here I changed it -->
</li>
Now change your function to accept the parameter and show that particular Text .
function toggleBannerText(section) {
if(section === "Over") {
// Switch to bannertext 2
bannerText1.className = 'hidebannertext'; // I have removed the +
bannertext2.className = 'welkom';
}
else if (section === "Home"){
bannertext2.className = 'hidebannertext'; // + has been removed
bannerText1.className = 'welkom';
}
else{
// none of the two buttons were clicked.
}
}
I have tested this code against your site and its working fine

Related

Find and Click button with JS

I'm trying to use a chrome extension (shortkeys) to create shortcut keys that can press buttons within our warehouse management system (so they can be matched to barcodes).
One of the buttons has no ID, and once it has been clicked the button innertext changes. Ideally I'd like the shortcut to work on either version of the button
It is either
<input type="submit" value="Create Shipment" class="btn btn-success pull-right">
or
<a class="btn btn-success" href="/Order/OrderDocumentP/15467" target="_blank">Print Label</a>
I then have another button to be assigned to a different shortcut key
<a class="btn btn-success" href="/Picking/DespatchOrder?OrderId=13413">Despatch</a>
But I'm sure once I've figured out the first one the next will be easier :)
Any help greatly appreciated, I've been through a number of other questions that are similar but not quite what I'm after and my JS knowledge is pretty rubbish
Learn CSS a bit and use https://developer.mozilla.org/ru/docs/Web/API/Document/querySelector
Your extensions probaply supports that
// cuz I don't like to type long "document.querySelector"
q = sel => document.querySelector(sel)
qq = sel => document.querySelectorAll(sel)
function clickOnly(sel) {
let list = qq(sel);
if (list.length == 1) list[0].click();
else alert('element "'+sel+'" is not unique!');
}
// handles *any* keypress
onkeypress = function (event) {
if (event.target.tagName == "INPUT") return; // noop on input focused
if (event.target.tagName == "TEXTAREA") return; // noop on input focused
console.log(event.code); // to see what the key is
let rawCode = event.code; // keyboard key, `KeyM` for M, `Digit7` for 7, `Slash` for /
let code = rawCode; // make CtrlAltShiftKeyM
if (event.shiftKey) code = 'Shift' + code;
if (event.altKey) code = 'Alt' + code;
if (event.ctrlKey) code = 'Ctrl' + code;
if (!kds[event.code]) return;
event.preventDefault(); // prevent CtrlKeyM browser handler for bookmarks or whatever
kds[event.code](event);
}
kds = {}
// it's a function so starts with `() => `
kds.KeyM = () => alert('it works!')
// a is for <a>, [href^=] is for href starts with
kds.ShiftKeyM = () => clickOnly('a[href^="/Order/OrderDocumentP/]')
// , is for one of multiple selectors
kds.CtrlKeyM = () => clickOnly('input[value="Create Shipment"], a[href^="/Order/OrderDocumentP/]')
This is a simple script on getting a button by class name and clicking it. I think this is what you are looking for, if not let me know I will rewrite it.
EDIT: I added a loop that will click all buttons or links found with the class name btn-success
I've inserted a second function so people looking for a solution by classname can also still find the first one. AutoClickBtnByValue() will click the button with inner text "click me now".
function AutoClickBtn() {
var button = document.getElementsByClassName("btn-success");
for (var i = 0; i < button.length; i++) {
button[i].click();
console.log('Success! Clicked button' + i);
}
}
setInterval(AutoClickBtn, 2000);
/* Click button by innerHTML text */
function AutoClickBtnByValue() {
var button = document.getElementsByClassName("btn-success");
for (var i = 0; i < button.length; i++) {
if (button[i].innerHTML.indexOf('click me now') > -1) {
button[i].click();
console.log('Success! Clicked button' + i + ' with value: "click me now" ');
}
}
}
setInterval(AutoClickBtnByValue, 2000);
<input type="submit" value="Create Shipment" class="btn btn-success pull-right">
<a class="btn btn-success" href="#" target="_blank">Print Label</a>
<a class="btn btn-success" href="#">Despatch</a>
<button class="btn-success">click me now</button>

Why document.querySelectorAll() returns null elements except the first one?

I need to select two elements (two tabs of five within a web) for click over them and scrap the tables returned.
Each tab is a 'li' and its child is a 'span' that contains the onclick event. I always get the list of tabs with the correct number of them but only the first element is not null, and even in the first element I can't call the onclick event to show me its tables. Also the 'id' that contains the onclick event is random.
I using phantomjs 2.1.1 and casperjs 1.1.4
JS code:
//Wait to be redirected to the Home page, and then make a screenshot
casper.then(function(){
casper.wait(5000, function(){
this.capture('home.png');
var tabs = casper.evaluate(function() {
//return document.querySelectorAll('[id^="dbTabLabel_"]'); //Another selector option
return document.querySelectorAll('span.dashTitle');
}
console.log('Num Tabs: ' + tabs.length););
for(i = 0; i < tabs.length; i++) {
if(tabs[i]) {
console.log('Form exists');
console.log('form id: ' + tabs[i].id);
// create a mouse click event
var event = document.createEvent( 'MouseEvents' );
event.initMouseEvent( 'click', true, true, window, 1, 0, 0 );
// send click to element
tabs[i].dispatchEvent( event );
var name = tabs[i].innerText + '.png'
casper.wait(2000, function(){ // Wait to load completely
this.capture(name); //Make a screenshot for each tab
});
} else {
console.log("Null Tab");
}
}
})
});
The output:
Num Tabs: 5
Form exists
form id: dbTabLabel_820718256523832
Null Tab
Null Tab
Null Tab
Null Tab
I want scrap this web (html code when I'm login in and save the web with getHTML casper function). The web screenshot here. And this is the fragment corresponding to the tabs:
<!--TEMPLATES-->
<ul id="tabul">
<li id="litab" class="ntabs add">+</li>
<li id="litab" class="add rightAlign setting-item">
<img src="/Content/images/icons/expand-24x24.png" class="out-triggerer gray" onclick="fullScreen()">
</li>
<li id="default-report-export" class="rightAlign">
<a href="/report/defaultExport" download="">
<input type="image" src="/Content/images/icons/excel.gif" value="Excel" title="Export default report">
</a>
</li>
<li id="default-report-export" class="rightAlign">
<a href="/report/defaultExport?isPdf=true" download="">
<input type="image" src="/Content/images/export-pdf-24x24.png" value="Excel" title="Export default report">
</a>
</li>
<li id="dbTab_889113733777776" class="ntabs addedTab activeTab">
<span id="dbTabLabel_889113733777776" class="dashTitle" onclick="clickDashboard('889113733777776')">Dashboard EUR</span>
<span id="dbTabSettings_889113733777776" class="settingsContainer dashSettings" style="">
<div id="topnav" class="topnav">
<a href="javascript:void(0)" class="signin" onclick="toggleTabSettingsMenu('889113733777776',true);">
<span><img src="/Content/Images/icon_gear.png" alt="Edit"></span>
</a>
</div>
<fieldset id="dbTabSettingsMenu_889113733777776" class="dashSettings-menu">
<ul class="dashboardEditMenu">
<img src="/Content/images/close.png" onclick="toggleTabSettingsMenu('889113733777776',false);" alt="tooltip" style="position:absolute;right:2px;top:2px;border:0;">
<li class="dashboardEditMenuList">
AƱadir widgets
</li>
<li class="dashboardEditMenuList">
Borrar este dashboard
</li>
</ul>
</fieldset>
</span>
</li>
<li id="dbTab_894967889413237" class="ntabs addedTab">
<span id="dbTabLabel_894967889413237" class="dashTitle" onclick="clickDashboard('894967889413237')">Dashboard USD</span>
<span id="dbTabSettings_894967889413237" class="settingsContainer dashSettings" style="display:none;">
<div id="topnav" class="topnav">
<a href="javascript:void(0)" class="signin" onclick="toggleTabSettingsMenu('894967889413237',true);">
<span><img src="/Content/Images/icon_gear.png" alt="Edit"></span>
</a>
</div>
<fieldset id="dbTabSettingsMenu_894967889413237" class="dashSettings-menu">
<ul class="dashboardEditMenu">
<img src="/Content/images/close.png" onclick="toggleTabSettingsMenu('894967889413237',false);" alt="tooltip" style="position:absolute;right:2px;top:2px;border:0;">
...
</ul>
</fieldset>
</span>
</li>
</ul>
I don't know if my problem is if my problem is related to this post I have read. But the proposed solution I can't do it because my 'ids' are random and I can't make "static" selectors for get them.
it's not an issue with document.querySelectorAll() because you have the right number of tabs in console.log('Num Tabs: ' + tabs.length);
it's because of the asynchronous casper.wait() here's an answer about asynchronous process in a loop
The for loop runs immediately to completion while all your
asynchronous operations are started. When they complete some time in
the future and call their callbacks, the value of your loop index
variable i will be at its last value for all the callbacks.
one way to work this out is to use use es6's let instead of var like
for(let i = 0; i < tabs.length; i++) { ... ES6 var vs let
or use .forEach since it creates its own function closure
for vs .forEach()
replace your for(i = 0; i < tabs.length; i++) { with tabs.forEach(function(tab)) { ..
and access the tab with tab instead of tabs[i]
here's a snippet to demonstrate it :
var tabs = ['tab1', 'tab2', 'tab3', 'tab4']
for(var i = 0; i < tabs.length; i++){
if(tabs[i]){
setTimeout(function(){ // simulating casper.wait
console.log('in the for loop with var : ' , tabs[i]);
}, 1000);
}
else{
console.log('none');
}
}
for(let i = 0; i < tabs.length; i++){
if(tabs[i]){
setTimeout(function(){ // simulating casper.wait
console.log('in the for loop with let : ' , tabs[i]);
}, 1000);
}
else{
console.log('none');
}
}
tabs.forEach(function(e){
if(e){
setTimeout(function(){ // simulating casper.wait
console.log('in the forEach loop : ' , e);
}, 1000);
}
else{
console.log('none');
}
})

How to Make Next and Previous Buttons to Switch iFrame Pages back and forth?

I made static ebook that when i click on a link it opens the html page in iFrame.Again, it is not dynamic pages.
I created Next and Previous Buttons in intend to work like that:
When the "pages/1.html" page displayed, i click on the Next button and it will display me the "pages/2.html" page at the iframe.
When i see "pages/2.html" and click the Previous button it will show me the "pages/1.html" at the iframe. And so on follow the numbers up and down.
I dont want to add those buttons on any iframe page i have, but to make Two Buttons ONLY at the main page that will direct to the Next and Previous Pages at the iframe.
Its kind of a simple code:
<div id="menu">
<ul>
<li><a class="link" href="./pages/1.html" target="content">Link 1</a></li>
<li><a class="link" href="./pages/2.html" target="content">Link 2</a></li>
<li><a class="link" href="./pages/3.html" target="content">Link 3</a></li>
<li><button onclick="next()">Next Page</button></li>
<li><button onclick="previous()">Previous Page</button></li>
</ul>
</div>
And the javascript is:
var pNum=1;
var maxPage=100;
function next(){
pNum++;
if (pNum > maxPage) pNum=1;
document.getElementById("zoome").src="page"+pNum+".htm";
}
function previous(){
pNum++;
if (pNum > maxPage) pNum=1;
document.getElementById("zoome").src="page"+pNum+".htm";
}
Here is a live code: JSFIDDLE
Right now i get an error page when i click the buttons and it is not forward me to any page.
Also, not that at the JSfiddle its not even forwarding to the next page because the page is not exist ofcourse.
Any suggestions?
Because you didn't provide in your fiddle an example of how we could try to simulate the paging. I searched the web and found a site which has articles separated by ids, similar to your scenario.
I focused on the next and previous functionality. The url is obviously different than that you provided, but you can easily adjust it to your needs.
Please, refer to the following snippet and see if it's what you need:
var pNum = 1;
var maxPage = 100;
document.getElementById("currentPage").innerHTML = pNum;
document.getElementById("pages").innerHTML = maxPage;
this.next = function() {
pNum++;
if (pNum > maxPage) pNum = 1;
document.getElementById("zoome").src = "https://www.infoq.com/articles/" + pNum;
document.getElementById("currentPage").innerHTML = pNum;
}
this.previous = function () {
pNum--;
if (pNum < 1) pNum = 1;
document.getElementById("zoome").src = "https://www.infoq.com/articles/" + pNum;
document.getElementById("currentPage").innerHTML = pNum;
}
<iframe id="zoome" height="150px" width="400px" allowfullscreen="" frameborder="0" border="0" src="https://www.infoq.com/articles/1"></iframe>
<div id="menu">
<ul>
<li>
<button onclick="next()">Next Page</button>
</li>
<li>
<button onclick="previous()">Previous Page</button>
</li>
<li>
Page <span id="currentPage"></span> / <span id="pages"></span>
</li>
</ul>
</div>
I got it to work via jquery from Here:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
var locations = ["1.html", "2.html", "3.html","4.html"];
var currentIndex = 0;
var len = locations.length;
$(document).ready(function(){
$(':button').click(function() {
currentIndex = this.value == "Next" ?
currentIndex < len - 1 ? ++currentIndex : len - 1 :
currentIndex > 0 ? --currentIndex : 0;
$('#frame').attr('src', locations[currentIndex]);
});
});
</script>
</head>
<body>
<input type = "button" value = "Previous" /> <input type = "button" value = "Next" />
<br />
<iframe id="frame" src="1.html"></iframe>
</body>
</html>
Work Perfect!!
More accurate is that:
var pNum=1;
var maxPage=100;
function next(){
pNum++;
if (pNum > maxPage) pNum=1;
document.getElementById("zoome").src="./pages/"+pNum+".html";
}
function previous(){
pNum--;
if (pNum > maxPage) pNum=1;
document.getElementById("zoome").src="./pages/"+pNum+".html";
}
Here is the JSfiddle
And now it works because i changed the ".htm" to ".html"
and the src (at the javascript) to "./pages/" and the src of the iframe to src="./pages/0.html"
I have try that method:
<script type="text/javascript">
var pages=new Array();
pages[0]="./pages/0.html";
pages[1]="./pages/1.html";
pages[2]="./pages/2.html";
pages[3]="./pages/3.html";
pages[4]="./pages/4.html";
var i=0;
var end=pages.length;
end--;
function changeSrc(operation) {
if (operation=="next") {
if (i==end) {
document.getElementById('zoome').src=pages[end];
i=0;}
else {
document.getElementById('zoome').src=pages[i];
i++;}}
if (operation=="back") {
if (i==0) {
document.getElementById('zoome').src=pages[0];
i=end;}
else {
document.getElementById('zoome').src=pages[i];
i--;}}}
</script>
It is have the same problem: when click on link at the menu that changes the iframe, the script stop working.
But! i saw the solution someone gave there but i didnt get how he was implement that.
Here's his answer:
This is the function that you could put before the changeSrc function:
function UpdateI(value) {i = value}
This the one click event that you would add to your links in the a
tag. Off course, the 4 that is sent the function in this case, would
be changed to whatever is appropriate for whatever ListItem is being
referenced:
onClick ="UpdateI(4)"
How do i implement that method he suggest?

Toggle on Yes/No buttons to continue on in survey

I want to know how to make sure either the Yes or No button is toggled in my survey in order to continue (so if either Yes or No has been clicked, the nextQuestion function can continue. If Yes or No has not been clicked, I will give an alert to the user to please make a selection). I currently have the progress bar and question updating in the same function. I figured it would make sense to add this bit to it but I am getting confused.
var index_question = 0;
var question_number = 2;
var progress_question = 1;
var percentage = 0;
function nextQuestion(){
if (index_question < 4) && ($(".btn-success").button('toggle')) {
<!-- Question # and Question Text -->
document.getElementById("questionArea").innerHTML = questionSet[index_question];
index_question ++;
document.getElementById("questionNum").innerHTML = [question_number];
question_number ++;
<!-- Progress Bar -->
percentage = ((([progress_question])*(100))/(5));
progress_question++;
$(".progress-bar").width([percentage] + "%");
}
<!-- Survey Completed -->
else {
$(".progress-bar").width("100%");
alert("Thank you for completing the survey!")
}
}
<td><button class="btn btn-success" type="button" onclick="questionDecision">Yes</button></td>
<td><button class="btn btn-danger" type="button" onclick="questionDecision">No</button></td>
function questionDecision() {
$(".btn btn-success").button('toggle');
$(".btn btn-danger").button('toggle');
}
One option is to have a variable in the Javascript like var answered_question = False;, which is set to True in your questionDecision function after they have made a choice. Before advancing the user to the next question or updating the progress bar, always check if(clicked_yes_or_no==True){ }.

deleting dynamically added DOM elements in IE6

My problem is that the DELETE ITEM (Item which has been added dynamically) is not deleteing by click in IE6.
javascript:
var TDCount = 3;
var i=0;
function insertTD(){
var possition=document.getElementById('elmnt_pos').value;
if(possition=="")
{
possition='a';
alert('Enter a number!!!');
}
if(isNaN(possition))
{
alert('Enter a number!!!');
document.getElementById('elmnt_pos').value='';
}else{
var newTD = document.createElement("li");
var newid='li'+TDCount++;
newTD.setAttribute("id", newid);
newTD.setAttribute("onclick","javascript:removenode(this);" );
var newText = document.createTextNode(i+"New fruit " + (possition++));
newTD.appendChild(newText);
var trElm = document.getElementById("menu");
var refTD = trElm.getElementsByTagName("li").item(possition-2);
trElm.insertBefore(newTD,refTD);
i++;
}
}
function removenode(th)
{
answer = confirm("Do you really want to Remove Element "+th.id + " ? ")
if (answer !=0)
{
document.getElementById('menu').removeChild(document.getElementById(th.id));
}
}
html
<ul id="menu">
<li id="li0" onclick="javascript:removenode(this);">apple</li>
<li id="li1" onclick="javascript:removenode(this);">Banana</li>
<li id="li2" onclick="javascript:removenode(this);">Jackfruit</li>
</ul>
<form name="justfrm">
<input type="text" value="Enter the position" name="pos1" id="elmnt_pos" />
<input type="button" value="click" onclick="javascript:insertTD()"/>
</form>
"Enter the position" means add element on a specific position like 2,3,5 etc.
We can Delete Item by click on item .
I don't have an instance on Internet Explorer 6 to test with, but more than likely it's this line, which is causing the problem:
newTD.setAttribute("onclick","javascript:removenode(this);" );
It does not work in Internet Explorer 6. You will need to do something like:
newTD.onclick = function() { removeNode(this); };
or
newTD.onclick = new Function("removenode(this)");
See this article for more information. Also, as a side note you may want to look into using a library like jQuery, which already handles these types of cross-browser issues.

Categories

Resources