Hiding button by "Id" works, but clicking it not - javascript

I execute the top portion here automatically.
In this script I can easily hide "showLine" via document.getElementById("showLine").style.visibility="hidden"; no problemo,
but document.getElementById("showLine").click(); will not fire no matter what I do...
The button does not press onload..
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
//Autoexecute on pageload
<script type="text/javascript">
$(document).ready(function () {
document.getElementById("showLine").click();
//document.getElementById("showLine").style.visibility="hidden";
});
</script>
//script with button "showLine"
<script>
var lines;
var randomNumber;
var lastRandomNumber;
$(document.body).ready(function () {
$.ajax({
url: "https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/Daymusic_array.js",
}).done(function (content) {
lines = content
.replace(/\r\n|\r/g, "\n")
.trim()
.split("\n");
lines = content
.replace(/\r\n|\r/g, "quote")
.trim()
.split("quote");
// ^^ line rmvl ^^^
if (lines && lines.length) {
$("#showLine").on("click", function () {
while (randomNumber === lastRandomNumber) {
randomNumber = parseInt(Math.random() * lines.length);
if (lines.length === 1) {
break;
}
}
lastRandomNumber = randomNumber;
$("#trivia").html(lines[randomNumber]);
});
}
});
});
</script>
<button id="showLine">CurrListening</button>
<p id="trivia"></p>
So how do I fix this clicking not working ?
PS:
I commented out the button, cause I used the visibility just for test purposes

You're executing click() before the AJAX request resolves.
I would suggest simply triggering a click after registering the listener.
$("#showLine")
.on("click", function () {
while (randomNumber === lastRandomNumber) {
randomNumber = parseInt(Math.random() * lines.length);
if (lines.length === 1) {
break;
}
}
lastRandomNumber = randomNumber;
$("#trivia").html(lines[randomNumber]);
})
.trigger("click");

You have to call it after their listener attached! First, you must add a listener and then trigger your click event.

Related

Preserve Navigation bar (Hide/Show) when navigated to Other module

How to preserve the navigation bar (minimized position) when navigated to other module.
Collapsed Navigation Bar
sidebar-collapse will not preserve if navigated to other page.
Do you want your nav-bar to change from big to small when you move to a different place?
(sorry, I'm not allowed to comment yet).
Do you want your nav-bar to change from big to small when you move to a different place? It is always nice if you add some code :)
const menuToggle = document.querySelector('.menu-toggle');
const mainUl = document.querySelector(".main-ul");
const navBtn = document.querySelectorAll(".nav-a");
// Open and close meny on click
menuToggle.addEventListener("click", function () {
menuToggle.classList.toggle("open");
mainUl.classList.toggle("open");
});
// Close menu when clicked on an a-tag in the menu
navBtn.forEach((button) => {
button.addEventListener("click", function () {
navBtn.forEach((button) => button.classList.remove("active"));
this.classList.add("active");
mainUl.classList.toggle("open");
menuToggle.classList.toggle("open");
});
});
This is demo and source code I created
https://minhhungit.github.io/2020/10/16/011-keep-menu-toggle-state-after-page-reload/
namespace J {
export function storageSet(name, val) {
if (typeof (Storage) !== "undefined") {
localStorage.setItem(name, val);
} else {
//window.alert('Please use a modern browser to properly view this template!');
}
}
export function storageGet(name) {
if (typeof (Storage) !== "undefined") {
return localStorage.getItem(name);
} else {
return null;
}
}
}
In _Layout.cshtml put this code
<script type="text/javascript">
$().ready(function () {
new DailyTimelog.Common.SidebarSearch($('#SidebarSearch'), $('#SidebarMenu')).init();
// ...
// ...
$(window).bind("load resize layout", doLayout);
doLayout();
});
</script>
// Add these lines
<script type="text/javascript">
let sidebarToggleButton = $('.main-header .sidebar-toggle');
if (sidebarToggleButton) {
$(sidebarToggleButton).on('click', function (e) {
e.preventDefault();
let isSidebarCollapse = $('body').hasClass('sidebar-collapse');
J.storageSet('IS_SIDEBAR_COLLAPSE', !isSidebarCollapse);
});
}
</script>
And LeftNavigation.cshtml
<script type="text/javascript">
function openWindow(url, width, height) {
height = height || (screen.availHeight - 60);
// ...
// ...
}
// Add these lines
let isSidebarCollapseCache = J.storageGet('IS_SIDEBAR_COLLAPSE');
if (isSidebarCollapseCache == 'true') {
$('body').toggleClass('sidebar-collapse', true);
}
else {
$('body').toggleClass('sidebar-collapse', false);
}
</script>
``
#minhhungit Thank you for your demo.
I have used cookie implementation similar to ThemePreference.
Views/Shared/_Layout.cshtml
var theme = !themeCookie.IsEmptyOrNull() ? themeCookie : "blue";
// Add following lines
var sbNavCookie = Context.Request.Cookies["SBNavigationPreference"];
var sbNav = !sbNavCookie.IsEmptyOrNull() && sbNavCookie == "true" ? true : false;
in Body Tag,
<body ... class="...#(sbNav?" sidebar-collapse":"")">
In Script Tag,
<script type="text/javascript">
$().ready(function () {
// Add new lines
let sidebarToggleButton = $('.main-header .sidebar-toggle');
if (sidebarToggleButton) {
$(sidebarToggleButton).on('click', function (e) {
e.preventDefault();
let isSidebarCollapse = $('body').hasClass('sidebar-collapse');
$.cookie('SBNavigationPreference', !isSidebarCollapse, {
path: Q.Config.applicationPath,
expires: 365
});
});
}

Function works only in debugger

I wrote the function for check if button was clicked twice and if it was to measure the time between two clicks. It has to prevent multiple clicks in short time.
Button click:
$("#Save").click(function () {
dateTime1 = new Date().getTime();
BtnId = this.id;
showSaveDialog();
});
And measuring function:
ButtonWasTriggeredTwice: function () {
var result = false;
var currentTime = new Date().getTime();
var time = currentTime - dateTime1;
if (PreviousBtn === null) {
result= false;
} else {
if (PreviousBtn === BtnId) {
if ( time < 1500) {
result = true;
}
else result = false;
}
else {
result= false;
}
}
PreviousBtn = BtnId;
BtnId = null;
return result;
}
BtnId and PreviosusBtn are global scope variables.
The strange thing is this function works great when I set breakpoints in debugger. If I switch off debugger function blocks every next click on button, no matter what time interval is between clicks
You can use this solution with unbind and timeout, like this:
HTML
<input type="button" id="Save" value="save me" />
JS:
function saveEventButton(){
$("#Save").click(function () {
alert('saved!');
$("#Save").unbind('click');
setTimeout(function(){
saveEventButton();
}, 5000); // 5sec
});
}
saveEventButton();
This is the JSFiddle
UPDATE This solution is a mix from mine and Revish Patel solution
function disableTimeout(_this){
$(_this).prop('disabled','disabled');
setTimeout(function(){
$(_this).prop('disabled','');
}, 5000); // 5sec
}
$("#Save").click(function () {
alert('saved!');
disableTimeout(this);
});
This is the JSfiddle
You can also disable button when you first click is performed.
$(document).ready(function () {
$("#Save").click(function(){
$('#Save').prop('disabled','disabled');
// Perform your button click operation
});
});

Hide DIVs after function has completed his task

I wrote a piece of code that auto replies to user text input.
An automated "live chat" so to say.
Though when the script runs out of responses I want it to disable the subit form and button, I don't really have any clue on how to do such a thing.
My code:
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("#typing").hide();
var n = "You:<br>";
var o = $('#outputWindow');
var i = $('#inputWindow');
var s = $('#sendButton');
var t = $('#typing');
var r = -1;
//arrays
var msg = ['msg1', 'msg2', 'msg3'];
//fire send events
$(s).click(function() {
runAI();
});
$(i).keydown(function(e) {
if (e.keyCode == 13) {
runAI();
}
});
function runAI() {
if (i.val().length > 0) {
r = r + 1;
o.html(o.html()+n+$("#inputWindow").val()+"<br><hr>" );
setTimeout(function(){ $("#typing").show(); }, 3000);
setTimeout(function(){ o.html(o.html()+"Username:<br>"+msg[r]+"<br><hr>") }, 7000);
setTimeout(function(){ $("#typing").hide(); }, 8000);
i.val('');
i.focus();
}
}
i.focus();
});
});//]]>
</script>
The idea is to hide the submit form and button after (in the case) the script has responded with: msg1, msg2 and msg3.
If anyone can help, that'd be great !
This will do that. Place at the bottom of the runAI() function.
this will check r+1 each time runAi() is invoked. When it detects that it's greater than or equal to the message array length it will hide the user input possibilities after the last message is sent.
function runAI() {
if (i.val().length > 0) {
r = r + 1;
o.html(o.html()+n+$("#inputWindow").val()+"<br><hr>" );
setTimeout(function(){ $("#typing").show(); }, 3000);
setTimeout(function(){ o.html(o.html()+"Username:<br>"+msg[r]+"<br><hr>") }, 7000);
setTimeout(function(){ $("#typing").hide(); }, 8000);
if (r+1 >= msg.length)
{
$('#inputWindow').hide();
$('#sendButton').hide();
return true; // end the function here;
}
else
{
i.val('');
i.focus();
}
}
}
When r reaches a length greater than or equal to the length of the array the input and button is hidden.
Well, simply use CSS to hide it:
$(<your object>).css('display', 'none');
use this for every object you want to hide. Go to www.w3schools.com and check out the posible values for the display property.

A .Click function not working in jQuery

What I need:
I need the button2 to appear when button1 is clicked. NEW STUFF: What I need it to do is save button2 there so if you refresh or "run" button 2 is already there how would I do that?
What I've done/Tried:
I've tried a bunch of different things such as changing it around changing the scope, as well as checking for console errors, I get none so I'm not too sure what is going on.
CODE
$(document).ready(function () {
$('#button2').hide();
window.highestLevel = 1;
$('#button1').click(function () {
Check();
highestLevel = 2;
});
if (highestLevel == 2) {
$('#button2').show();
}
function Check() {
localStorage.setItem('highestLevel', highestLevel);
}
});
WHAT WORKS
The only thing that works is it stores it correctly to the html local storage when I click $('#button1').
Link , jsFiddle
For this to work as you describe, the if-structure ...
if (highestLevel == 2) {
$('#button2').show();
}
... must be inside the click function. Try ...
$('#button1').click(function () {
Check();
highestLevel = 2;
$('#button2').show();
});
You really don't need the if-structure doing it this way ... in your code, the if-structure only runs on document-ready (ONE TIME).
You are mistaken about what is happening. This code block runs when the document is loaded, not after button1 is clicked.
You want to put it inside the click function
$('#button1').click(function () {
Check();
highestLevel = 2;
if (highestLevel == 2) {
$('#button2').show();
}
})
You will also want to prevent the default action of the button, which is to post the page causing it to reload, by adding an event object
$('#button1').click(function (e) {
e.preventDefault();
Check();
highestLevel = 2;
if (highestLevel == 2) {
$('#button2').show();
}
})
});
You don't need all of that... The problem is that
if (highestLevel == 2) {
$('#button2').show();
}
executes only once, when the document is ready.
Try this:
$(document).ready(function () {
$('#button2').hide();
$('#button1').click(function () {
$('#button2').show();
});
});
Try with this
window.highestLevel = localStorage.getItem('highestLevel');
$(document).ready(function () {
if (highestLevel == 2) {
$('#button2').show();
$('#button1').hide();
}
else {
highestLevel == 1
$('#button1').show();
$('#button2').hide();
}
$('div').click(function () {
if (highestLevel == 2) {
highestLevel = 1;
$('#button1').show();
$('#button2').hide();
}
else{
highestLevel = 2;
$('#button2').show();
$('#button1').hide();
}
Check();
});
});
function Check() {
localStorage.setItem('highestLevel', highestLevel);
}

How to click a Button with specific text?

I am trying to modify the script below to click a button that looks like this on a site:
<button id="checkPrice-02070" onclick="checkPrice(02070,null); return false;" class="orangeDark">
<span>check price</span>
</button>
I am using the code below. So far, the page seems to keep reloading; nothing else happens.
Any advice to someone new?
(function () {
window.addEventListener("load", function (e) {
clickConfirmButton()
}, false);
})();
function clickConfirmButton() {
var buttons = document.getElementsByTagName('button');
var clicked = false;
for (var index = 0; (index < buttons.length); index++) {
if (buttons[index].value == "check price") {
buttons[index].click();
clicked = true;
break;
}
}
if (!clicked) {
setTimeout("window.location.reload()", 300 * 1000);
}
}
A <button>s value is not the visible text. You'd want to search textContent.
However:
If that sample HTML is correct, you'd be better off searching for ids that start with checkPrice. See the code below.
Are you sure you want to reload if the button is not found? If it is added by AJAX this is not the best approach. See this answer.
Don't use setTimeout with a string (to evaluate) argument like that. See the code below.
You do not need to wrap the code in an anonymous function.
Anyway, this should work, given the sample HTML:
window.addEventListener ("load", clickConfirmButton, false);
function clickConfirmButton (zEvent) {
var button = document.querySelector ("button[id^='checkPrice']");
if (button) {
button.click ();
}
else {
setTimeout (function () { location.reload(); }, 300 * 1000);
}
}
To check the button text anyway, use:
function clickConfirmButton (zEvent) {
var buttons = document.querySelectorAll ("button[id^='checkPrice']");
var clicked = false;
for (var index = 0, numBtn = buttons.length; index < numBtn; ++index) {
if (/check price/i.test (buttons[index].textContent) ) {
buttons[index].click();
clicked = true;
break;
}
}
if (!clicked) {
setTimeout (function () { location.reload(); }, 300 * 1000);
}
}

Categories