How do I swap one div with another on a certain time - javascript

I have 2 divs (#divA & #divB). I want one to display #divA, then on a certain date hide divA, and show #divB.
DivA would represent 'Coming soon' and DivB would represent 'Now Here!'

Try something like :
if (new Date() < new Date(2013,1,1)) {
document.getElementById("diva").style.display = "block";
document.getElementById("divb").style.display = "none";
} else {
document.getElementById("diva").style.display = "none";
document.getElementById("divb").style.display = "block";
}
This checks if todays date (new Date()) is before a selected date (new Date(2013,1,1)) if it is then it shows diva and hides (display = "none") divb - else the reverse

You can set display:none to hide the Div and display:block to show it
<div id="divA" style="display:none;">Coming Soon </div>

use setInterval() to achieve that, e.g,
assuming you are using jQuery and the page should look like:
<div id="A"> comming soon</div>
<div id="B" style="display:none"> Now here! </div>
<script>
function check_if_some_content_is_loaded(){
//your implementation code here...
is_loaded = ....
if(is_loaded){
$("#A").toggle();
$("#B").toggle();
}
}
$(function(){
// call the "check ..." function every 10 seconds.
setInterval("check_if_some_content_is_loaded()", 10000);
})
</script>

You have to use a server site technology like php, i think. No use of loading all the stuff to client side. Your web page will be slow. Just see if possible to use php.

Related

In a pinch, stuck in a simple onclick text cycle

For a project, I'm trying to highlight the logical fallacy of circular reasoning and have precious few lines of code later to be inserted into a separate webpage.
I am trying to create a simple process of clicking the displayed text to switch back and forth between the two questions. I've tried buttons and it only complicates and make no progress. Half a day gone, still banging my head on desk, as the phrase goes.
I read elsewhere that creating a var tracker facilitates, though I see it only for images, rather than displayed text. It feels like approaching my wits end, but I lack the time to walk away and try again.
This is my code thus far:
<!doctype html>
<head>
<script>
function change() {
var paragraph = document.getElementById("whytrust");
paragraph.innerHTML="I am trustworthy, but how can you be sure?";
}
</script>
</head>
<body>
<p id="whytrust" onclick="change();">You can trust me, but how can you be sure?</p>
</body>
</html>
You need some place to hold the old message so you can put it back again after you toggle the contents.
<!doctype html>
<head>
<script>
var newMsg = "I am trustworthy, but how can you be sure?";
function change() {
var paragraph = document.getElementById("whytrust");
var oldMsg = paragraph.innerHTML;
paragraph.innerHTML = newMsg;
newMsg = oldMsg;
}
</script>
</head>
<body>
<p id="whytrust" onclick="change();">You can trust me, but how can you be sure?</p>
</body>
</html>
This a quick and dirty implementation of what you want. I added a data-textindex attribute to the html element. There I stored an index for the currently shown text. In the javascript I check the current value, update data-textindex and replace it with new text.
function change() {
let paragraph = document.getElementById("whytrust");
let currentlyshown = paragraph.getAttribute('data-textindex');
if(currentlyshown == 0){
paragraph.innerText="I am trustworthy, but how can you be sure?";
paragraph.setAttribute('data-textindex', '1');
}else if(currentlyshown == 1){
paragraph.innerText="You can trust me, but how can you be sure?";
paragraph.setAttribute('data-textindex', '0');
}
}
<p id="whytrust" data-textindex="0" onclick="change();">You can trust me, but how can you be sure?</p>
On a sidenote: You can improve this code a lot. Like storing your text in a json-object. Or maybe using the ternary operator if you are 100% sure there will always be 2 choices. maybe give the function some arguments so you can apply it in a more general scenario.
Try tracking some sort of 'state' for your paragraph -- be it on/off, active/inactive...
Each time the change() function gets called, it doesn't remember what the paragraph was or was supposed to be. So, by setting a state of some sort (in my example a data-state attribute assigned to the paragraph element) the code can know how to behave.
function change() {
var paragraph = document.getElementById("whytrust");
var output = '';
// data-* can be anything, but handy for referencing things
var state = paragraph.getAttribute('data-state');
// check if data-state even exists
if( !state ){
// set it to the default/original state
paragraph.setAttribute('data-state', 'inactive');
state = 'inactive';
}
// toggle the state
// and assign the new text
if( state === 'inactive' ){
paragraph.setAttribute('data-state', 'active' );
output = "I am trustworthy, but how can you be sure?";
}else{
paragraph.setAttribute('data-state', 'inactive');
output = "You can trust me, but how can you be sure?";
}
paragraph.innerHTML = output;
}
<p id="whytrust" onclick="change();">You can trust me, but how can you be sure?</p>
Another option, without tracking state could be hiding and showing the paragraph you want displayed. You don't really need to track state or save the alternating text...
// get the elements from the DOM that you want to hide/show
// you can get tricky and add alternative ways to track
// the paragraph elements, but this works nice for a demo
const whytrust = document.getElementById('whytrust'),
answer = document.getElementById('whytrust-answer');
function change( element ){
// the element parameter being passed is the paragraph tag
// that is present/visible
if( element.id === 'whytrust' ){
answer.className = ''; // clear the .hide class
whytrust.className = 'hide'; // add the .hide class
}else{
whytrust.className = ''; // clear the .hide class
answer.className = 'hide'; // add the .hide class
}
}
.hide{ display: none; }
<p id="whytrust" onclick="change(this);">I am trustworthy, but how can you be sure?"</p>
<p id="whytrust-answer" class="hide" onclick="change(this);">You can trust me, but how can you be sure?</p>
What I like about this solution is that it keeps the content in the HTML and the JavaScript just worries about what to hide/show.

Show DIV On Highlight Then Hide

I'm attempting to have a hidden div tag display when highlighting specific text. I was able to get a hidden div to display on highlighting but the 2 parts I cannot accomplish are:
Only show when highlighting specific text (I assume using a span tag id or something similar)
After the display has been changed to block, change it back to hidden after 5 seconds.
Here is my attempt. Again, this does show the hidden div on highlighting but that's as far as I got. Please help!
function ShowNote() {
document.getElementById('Note').style.display = 'block';
}
document.onmouseup = ShowNote;
if (!document.all) document.captureEvents(Event.MOUSEUP);
function HideNote() {
document.getElementById('Note').style.display = 'hidden';
}
setTimeout("HideNote()", 5000); // after 5 secs
I DON'T want it to show when I highlight this text
<br />I DO want it to show when I highlight this text.
<div type='text' id='Note' style="display:none;">HIDDEN DIV CONTENT</div>
You're very close!
Here's what I have:
function ShowNote() {
if(window.getSelection() == "I DO want it to show when I highlight this text.")
document.getElementById('Note').style.display = 'block';
setTimeout(function(){
document.getElementById('Note').style.display = 'none';
}, 5000); // after 5 secs
}
document.onmouseup = ShowNote;
if (!document.all) document.captureEvents(Event.MOUSEUP);
I DON'T want it to show when I highlight this text<br />
I DO want it to show when I highlight this text.
<div type='text' id='Note' style="display:none;" >HIDDEN DIV CONTENT</div>
Changes:
You need to check what is highlighted via the "window.getSelection()"
function.
You were passing a string to setTimeout
hidden isn't a valid display option, none is
So you know, it's generally bad practice to just have text floating around outside of tags. So it's best to stick your first two lines in <p> tags or something.
You are using quite old and antiquated code. Here's the modern approach:
function showNote() {
document.getElementById('Note').classList.remove("hide");
setTimeout(hideNote, 5000); // after 5 secs
}
function hideNote(){
document.getElementById("Note").classList.add("hide");
}
document.getElementById("select").addEventListener("mouseup", showNote);
.hide { display: none; }
#select { color:red; }
<div>I DON'T want it to show when I highlight this text</div>
<div>I DO want it to show when I highlight <span id="select">this text</span>.</div>
<div type='text' id='Note' class="hide">HIDDEN DIV CONTENT</div>
This is what I did for you.
I setup interval. that occurs every time you mouse out.Or even better it will check if it's your div's style is block on the page.
Hope this helps
Live exapmle on Codepen
var target = document.getElementById('note');
var i = setInterval(function(){
if (document.getElementById("note").style.display == 'block') {
hide();
}
}, 5000);
function showNote() {
target.style.display = 'block';
}
function hide(){
document.getElementById("note").style.display = "none";
}

JavaScript Library needed for Showing/Hiding a div panel using JQuery

I have a simple fieldset and div panel, which I want to initially show. If you then click on a button/image or text I then want to hide the div panel. Let's call this "myPanel". Clicking on the button/image or text once more will then show it again. Now I have a solution in JavaScript below, but my question is how can I create a library for this and re-use this instead of writing out the method's for multiple panels. Something similar to this:
var panel = new library.panel("myPanel");
Then all events will be handled and variables defined in the JavaScript library.
Consider the following code:
<fieldset>
<legend>My Panel<a id="MyPanelExpandCollapseButton" class="pull-right" href="javascript:void(0);">[-]</a></legend>
<div id="MyPanel">
Panel Contents goes here
</div>
</fieldset>
<script type="text/javascript">
//This should be inside the JavaScript Library
var myPanelShown = true;
$(document).ready(function () {
$('#MyPanelExpandCollapseButton').click(showHideMyPanel);
if (myPanelShown) {
$('#MyPanel').show();
} else {
$('#MyPanel').hide();
}
});
function showHideMyPanel() {
if (myPanelShown) {
$('#MyPanelExpandCollapseButton').text("[+]");
$('#MyPanel').slideUp();
myPanelShown = false;
} else {
$('#MyPanelExpandCollapseButton').text("[-]");
$('#MyPanel').slideDown();
myPanelShown = true;
}
}
</script>
If you want to make it yours then it is simple, make a function in separate js file :
function showHideBlock(panelId, buttonId){
if($(panelId).css('display') == 'none'){
$(panelId).slideDown('normal');
$(buttonId).text("[+]");
}
else {
$(panelId).slideUp('normal');
$(buttonId).text("[-]");
}
}
Now pass the panel or block id which you want to hide/show and button id which will cause hide/show.
onclick="showHideBlock('#MyPanel', '#MyPanelExpandCollapseButton');"
Try this
create a separate .js file and include it in whichever page you want. however remember to keep the id same :3

refreshing div every 10 second duplicate the div

I'm using jquery it auto refresh after 10 seconds and every time it refresh it duplicate the div for one time and refresh both of the div's again.
the duplicate happens only one time ..
code:
<div class="tournament-users">
<span class="tournament_reg_teams_num">0/8></span>
</div>
js :
<script type="text/javascript">
var autoLoad = setInterval(
function ()
{
$('.tournament_reg_teams_num').load('normal-l.php .tournament_reg_teams_num').fadeIn(\"fast\");
}, 10000); // refresh page every 10 seconds
</script>
and what i get after 10 seconds is :
<div class="tournament-users">
<span class="tournament_reg_teams_num">0/8></span>
<span class="tournament_reg_teams_num">0/8></span>
</div>
Thanks for the help! :)
Before appeding you have to flush div content using empty().
Please try
$('.tournament-users').empty();
Try using an id instead of a class. Also you could try to build a wrapper for your tournament_reg_teams_num and load it into that.
Try something like this for example:
HTML
<div id="wrapper_tournament_reg_teams_num">
<span id="tournament_reg_teams_num">0/8</span>
</div>
JS
var autoLoad = setInterval(
function ()
{
$('#wrapper_tournament_reg_teams_num').load('normal-l.php #tournament_reg_teams_num').fadeIn(\"fast\");
}, 10000);
HTML:
<div class="test">
<div class="test2">test2</div>
</div>
JS:
var count = 0;
//function autoload : it return the setInterval function
var autoload = setInterval(function(){
//(You can do what you want here, depending on what you want to do)
count += 1;
//Here, I remove the content of "test" element
$('.test').empty();
//I create the new element and add it to "test" element
var element = $('<div></div>').addClass('test2').html('test2');
$('.test').append(element);
console.log(refresh);
}, 10000);
//If you have to stop the refresh
setTimeout(function(){
console.log('clearInterval');
clearInterval(autoload);
}, 6000)
This is only an exemple of auto refresh, hope it can help you !

Javascript if else statement to hide and show div

Please refer to the following codes :
<div id="message-1" onclick="javascript:showresponddiv(this.id)>
</div>
<div id="respond-1" style="display:none;">
</div>
<div id="message-2" onclick="javascript:showresponddiv(this.id)>
</div>
<div id="respond-2" style="display:none;">
</div>
<script type="text/javascript">
function showresponddiv(messagedivid){
var responddivid = messagedivid.replace("message-", "respond-");
if (document.getElementById(responddivid).style.display=="none"){
document.getElementById(responddivid).style.display="inline";
} else {
document.getElementById(responddivid).style.display="none";
}
}
</script>
The codes above already success make the respond div appear when user click on message div. The respond div will disappear when user click on message div again. Now my question is how to make the respond div of 1st message disappear when user click on 2nd message to display the respond div of 2nd message?
You should give the "respond" divs a common class:
<div id="respond-1" class="response' style="display:none;"></div>
Then you can get all divs by using getElementsByTagName, compare the class and hide them on a match:
function hideAllResponses() {
var divs = document.getElementsByTagName('div');
for(var i = divs.length; i-- ;) {
var div = divs[i];
if(div.className === 'response') {
div.style.display = 'none';
}
}
}
We cannot use getElementsByClassName, because this method is not supported by IE8 and below. But of course this method can be extended to make use of it if it is supported (same for querySelectorAll). This is left as an exercise for the reader.
Further notes:
Adding javascript: to the click handler is syntactically not wrong but totally unnecessary. Just do:
onclick="showresponddiv(this.id)"
If you have to do a lot of DOM manipulation of this kind, you should have a look at a library such as jQuery which greatly simplify such tasks.
Update: If always only one response is shown and you are worried about speed, then store a reference to opened one:
var current = null;
function showresponddiv(messagedivid){
var id = messagedivid.replace("message-", "respond-"),
div = document.getElementById(id);
// hide previous one
if(current && current !== div) {
current.style.display = 'none';
}
if (div.style.display=="none"){
div.style.display="inline";
current = div;
}
else {
div.style.display="none";
}
}
Edit: Fixed logic. See a DEMO.
You can add some class to all divs with id="respond-"
e.g
<div id="respond-1" class="classname" style="display:none;"></div>
<div id="respond-2" class="classname" style="display:none;"></div>
Now at first row of your function "showresponddiv()" you should find all divs with class "classname" and hide them.
With jQuery it is simple code:
$(".classname").hide();
jQuery - is a Javascript Library that helps you to easy manipulate with DOM and provides cross-browser compatibility.
Also you can look to Sizzle - it is a JavaScript CSS selector engine used by jQuery for selecting DOM elements

Categories