Get a dynamic element to change text - javascript

I have a dynamic element in my web page like this that appear when I click on an icon:
<span class="elasticbar-item text-right text-baseline">
<button class="button primary" data-next-button="">MY TEXT</button>
</span>
But I want to change default text that come from server (where I don't have access) with a new text.
What I tried before now is represented by:
var buttonIntervalCheck = setInterval(function () {
var button = $("[data-next-button]");
if(button.length === 1) {
button.text("NEW TEXT");
clearInterval(buttonIntervalCheck);
}
}, 1000);
Example in Google Chrome
First result is when I clicked on my icon.
Second result is when I make Inspect on the button (Ctrl+Shift+I) on the button.
And I don't understand how exactly works.
How I can fix it?

Try running this on your console:
$("[data-next-button]").text("NEW TEXT");
If it works correctly, then your timing is wrong. You are probably calling button.text before the DOM has loaded. Try wrapping your code around the ready fuction:
$(function() {
var buttonIntervalCheck = setInterval(function () {
var button = $("[data-next-button]");
if(button.length === 1) {
button.text("NEW TEXT");
clearInterval(buttonIntervalCheck);
}
}, 1000);
});

You can't select a dynamic element with jquery , try with js like
document.querySelector("[data-next-button]")

In the example below there is a setTimeout() that adds the button in the HTML dynamically in 5 seconds. Then, the setInterval() changes the text of the button and close the interval. Everything worked as you expected. I don't see any error here.
var buttonIntervalCheck = setInterval(function () {
var button = $("[data-next-button]");
if(button.length === 1) {
button.text("NEW TEXT");
clearInterval(buttonIntervalCheck);
}
}, 1000);
setTimeout(function(){
$('#ss').html(`<span class="elasticbar-item text-right text-baseline">
<button class="button primary" data-next-button="">MY TEXT</button>
</span>`);
}, 5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='ss'></div>

Related

automatically clicking a button in javascript

I have this button:
<button class="btn btn-primary" type="button">Display</button>
and I'd like to click automatically that button every 100ms, I wrote this script but it doesnt work:
window.onload = function(){
var button=document.getElementsByClassName("btn btn-primary");
setInterval(function(){
button.click();
}, 100);
)
getElementsByClassName return a NodeList instead of an Element. Try to use querySelector
window.addEventListener('load', function () {
var button = document.querySelector(".btn.btn-primary");
setInterval(function () {
button.click();
}, 100);
});
If you want apply with all matched buttons, you can use querySelectorAll and [].slice.call to convert NodeList to Array
window.addEventListener('load', function () {
var buttonList = document.querySelectorAll(".btn.btn-primary");
var buttons = [].slice.call(buttonList);
setInterval(function () {
buttons.forEach(function (button) {
button.click();
});
}, 100);
});
For making a button click automatically, it is better to pass the function in setInterval Method.
setInterval(function(){
alert('Working fine'); //Same function as it was supposed on click
}, 5000);
To see the working model, I have attached a JS Fiddle to it.
https://jsfiddle.net/xrefwqcj/2/
Many selectors can yield multiple results, so you must specify an index to work with a selected element. If there is only one result the index will be [0].
window.onload = function(){
var button=document.getElementsByClassName('btn btn-primary')[0];
setInterval(function(){
button.click();
}, 100);
}
Also if this script runs before your button has loaded, the selector will not yield any results and could produce an error - here is one solution for that:
window.onload = function(){
setInterval(function(){
if (typeof document.getElementsByClassName('btn btn-primary')[0]!="undefined"){
document.getElementsByClassName('btn btn-primary')[0].click();
}
}, 100);
}
The above script will repeatedly check whether the selected element is defined before clicking it (then continue to do so indefinitely since you don't have any mechanism to toggle it off). You also had a ")" at the last line of your sample code which I think should have been a "}".

Jquery / JavaScript boostrap Switchery clearInterval doesn't work

I have a boostrap switchery on my site:
<div class="form-group">
<label class="checkbox-inline checkbox-right checkbox-switchery switchery-sm">
<input type="checkbox" class="switchery" id="test55">
Live
</label>
</div>
<div id="tableHolder"></div>
I want to achive this:
on page load load external page into "tableHolder" div.
Switchery is default turned off.
When you click on switchery, load the same external page, but with div resfresh every 5 seconds.
If you turn off switchery, show only loaded external page, without resfresh interval.
I'm having troubles, because everything works ok, but when i press switchery to off, the div still keeps refreshing, so clearInterval doesnt' work :(
Here is my script:
<script type="text/javascript">
$(document).ready(function () {
$('#tableHolder').load('external.php?name=myId001')
var documentInterval = 0;
$('#test55').change(function () {
if ($(this).prop("checked")) {
documentInterval = setInterval(function () {
$('#tableHolder').load('external.php?name=myId001')
}, 3000);
} else {
clearInterval(documentInterval)
}
});
});
</script>
Use click, not change function.
$(document).ready(function() {
$('#tableHolder').load('external.php?name=myId001');
var elem = document.querySelector('#test55');
var init = new Switchery(elem);
var documentInterval = 0;
var clickCheckbox = document.querySelector('#test55');
$(document).on('click', '#test55', function() {
if ($(this).prop("checked")) {
documentInterval = setInterval(function() {
$('#tableHolder').load('external.php?name=myId001');}, 3000);
} else {
clearInterval(documentInterval);
}
});
});
Sample fiddle here . This will append some text to the div as when switch is on and will stop appending when switch is turned off. If you change the 'click' event to 'change' event the text appending will continue even when the switch is off

Click on div with javascript or jquery

I have a clickable div and I want to some how with javascript or jquery to be able to click on it automatically.
My div is like this:
<div style="display:none;" id="button">Hello</div>
That is click able div when display changed to block I need some script to do that for me.
I need some script like, when it sees that div display changed to block then script must click on div id="button"
I have tried this but this is not for that as I searched on google
<script type="text/javascript">
$(document).ready(function(){
$('#button').trigger('click');
});
</script >
Here is an example in JS:
<div style="display:none;" id="button">Hello</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
var button = document.getElementById('button');
button.addEventListener('click', function() {
this.style.display = 'block';
})
if (button.style.display === 'block') {
button.click()
}
});
</script >
Update:
If you need to click on button after some javascript actions, just add there following lines:
if (button.style.display === 'block') {
button.click()
}
Update2:
In the provided page I found the method to show mentioned div:
function startChecking() {
secondsleft -= 1e3,
document.querySelector(".load_stream").innerHTML = "Please Wait.. " + Math.abs(secondsleft / 1e3) + " Seconds",
0 == secondsleft && (clearInterval(interval),
$(".reloadframe").show(),
document.querySelector(".load_stream").style.display = "none",
$("#btn_play_s").show()
//You need to place it here, after "show" div will be displayed
// and display will have value "block"
)
}
So you can replace last line with $('#btn_play_s').show().click() instead of $('#btn_play_s').show(), it will be enough.
Simply use $('#button').click(); every where you want.
If you want to trigger this event when button display changed first you need create an event for this (because Jquery don't have on display changed event).
And then trigger it's your self:
$('#button2').on('click',function(){
$('#button')
.css('display','block')
.trigger('isVisible');
});
$('#button').bind('isVisible',function() {
alert('Clicked...!');
});
$(function(){
$('#button').click();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="button2" value="display the button"/>
<div style="display:none;" id="button">Hello</div>

Call a function in javascript only after page load

I have a button that is set up to call a javascript function to automatically activate a "tab" on a page. When that tab is loaded, there are subtabs that display. I am trying to set it up so that one of the subtabs is also automatically activated when the button is clicked.
Currently I can get the first tab to select, but I can't get the subtab to select. #detailsTab is the id of the first tab. #personal-information is the id of the subtab I am trying to select.
The following is what I have.
This is all in the same file:
HTML:
<button class="button button--primary button--sm" onclick="viewDetials()">View Details</button>
Javascript:
<script type="text/javascript">
function viewDetials() {
$("#detailsTab").click();
personalSubTab();
}
window.onload = function personalSubTab() {
$("#personal-information").click();
}
</script>
Try combining your functions and adding a short delay for the subtab.
function viewDetials() {
$("#detailsTab").click();
setTimeout(function(){
$("#personal-information").click();
}, 200); // This value can be tweaked
}
The following will be called when the document is ready.
<script type="text/javascript">
function viewDetials() {
$("#detailsTab").click();
personalSubTab();
}
function personalSubTab() {
$("#personal-information").click();
}
// Document ready
$(function () {
personalSubTab();
});
</script>
I'm not exactly sure what you want to do - but if you want to generate a click event on another button/div use trigger, not click - like this:
function personalSubTab() {
$("#personal-information").trigger('click');}

How to execute .click() code when previous click binding finishes

I am trying to use a Twitter Bootstrap button group with data-toggle="buttons-radio" in my site. Bootstrap markup as follows.
<div class="btn-group program-status" data-toggle="buttons-radio">
<button class="btn">All</button>
<button class="btn">Active</button>
<button class="btn">Planning</button>
<button class="btn">End of Life</button>
<button class="btn">Cancelled</button>
</div>
I need to redirect to the same page with query depending on the pressed button. I tried to use following jQuery code to achieve this.
<script>
var sParamStr = '';
function addToParamStr(str) {
sParamStr += str;
}
function redirectToUpdatedLocation() {
$('.program-status > .btn.active').each(function () {
addToParamStr( '?status=' + $(this).text());
});
console.log(sParamStr);
window.location.href = "program" + sParamStr;
}
$document.ready(function () {
$('.program-status > .btn').on('click', function (e) {
redirectToUpdatedLocation();
});
});
</script>
But the browser always redirects to {site}/program without the query string. By commenting out window.location.href = "program" + sParamStr; line, I managed to observe that second click onwards, sParamStr getting appended properly.
It seems that, my code tries to read the text of the pressed button before, .button('toggle') method form bootstrap.js finished. Code worked as intended when I changed function as follows.
$document.ready(function () {
$( '.program-status > .btn').on('click', function (e) {
$(this).addClass('active');
redirectToUpdatedLocation();
});
});
While this method works for me right now, I would like to know the proper way to achieve this. i.e How to execute my code after previous click binding finishes?
UPDATE:
I found this link in the Twitter Bootstrap forum. Seems it is a known issue.
https://github.com/twitter/bootstrap/issues/2380
I'm not sure what Bootstrap's .toggle is doing exactly, but it seems like it does some sort of animation that completes with the setting of the active class. You can try enqueing your code instead:
$( '.program-status > .btn').on('click', function (e){
$(this).queue(function (next) {
redirectToUpdatedLocation();
next();
});
});
For example, click the div as it is being toggled: http://jsfiddle.net/9HwYy/
It also seems a bit silly to me to update every href instead of just the one you clicked on since you are changing the window location anyway.
try
$('.program-status > .btn.active').each(function(i,v){
v = $(v);
addToParamStr( '?status=' + v.text());
});
since im not sure "this" is working in your case.

Categories