Trying to pick div randomly, but it echo empty div sometimes? - javascript

I am trying to pick div randomly. The only issue in my code is that it will randomly pick one empty div sometimes. I don't understand why it will echo one empty div sometimes. I have use chrome inspect element to check, there is no empty div. What did I do wrong on the foreach loop.
var divs = $(".widget").get().sort(function(){
return Math.round(Math.random())-0.5; //so we get the right +/- combo
}).slice(0,1);
$(divs).show();
.widget{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
foreach ($widgets as $widget){
echo'<div class="widget" >';
echo $content;
echo'</div>';
}
?>

There's no need for any weird sort function to get a random element out of the jQuery collection. Here's one way to do it with eq.
var $widgets = $('.widget');
var length = $widgets.length;
var div = $widgets.eq(Math.floor(Math.random() * length));
div.show();
.widget {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget">1</div>
<div class="widget">2</div>
<div class="widget">3</div>
<div class="widget">4</div>
<div class="widget">5</div>
<div class="widget">6</div>
<div class="widget">7</div>

Related

Using a stored TimeLapse stored in a datatable inside a php while loop

I am trying to display images from a database with a time delay between each image. The time delay is selectable from the user interface
and stored in seconds in the same record as the image. I aalready have the images displaying but I need to incororate the dynamic time delay.
The time delay is stored in a field named "TimeLapse". Below I have tried to used the content of "TimeLapse as $HoldTime each time
the while loop display a new image.
Image one has a TimeLapse of "5000".
Image two has a TimeLapse of "15000".
But it looks like it's only using the first TimeLapse of 5000 for both images."
Can anyone see how I can do this.
PHP CODE
while($row_fb = mysqli_fetch_array($fb)){ ?>
<?php $url = $ImagePath.''.$row_fb['SignageImageName'];
$HoldTime = $row_fb['TimeLapse']?>
<div class="outer">
<div class="banner-container">
<div id="wrapper">
<a><img src="/<?php echo $url;?>" class="responsive"/></a>
</div>
</div>
</div>
<?php
}
JAVASCRIPT
(function() {
var a = $('.outer').children();
var index = 0;
run()
function run() {
a.filter('.active').fadeOut(500).removeClass('active');
a.eq(index).fadeIn(500).addClass('active');
index = (index + 1) % a.length;
setTimeout(run, <?php echo $HoldTime;?>);
}
})();
I would put the delay time into an HTML data- attribute and read it in the JavaScript to set the delay. (Note use of alternative syntax and short echo tags, this makes your PHP code more readable when mixed with HTML.)
<?php while($row = $fb->fetch_array()): ?>
<div class="outer">
<div class="banner-container" data-delay-time="<?=$row['TimeLapse']?>">
<div id="wrapper">
<a>
<img src="/<?=$ImagePath . $row['SignageImageName']?>" class="responsive"/>
</a>
</div>
</div>
</div>
<?php endwhile ?>
The JS has been cleaned up to eliminate any dependency on variables from outside the function. Instead it just looks for the active banner's next sibling, looping to the beginning if it doesn't have one. Some test HTML is included for a runnable example.
(function() {
$("div.outer div.banner-container").hide();
run();
function run() {
// get a list of all the banners
var banners = $("div.outer div.banner-container");
if (!banners.length) {
return;
}
// active is the one with "active" class, or the first one
var active = banners.filter(".active").first();
if (!active.length) {
active = banners.first();
}
// get the next one or loop to the beginning again
var next = active.next("div.banner-container");
if (!next.length) {
next = banners.first();
}
active.fadeOut(500).removeClass("active");
next.fadeIn(500).addClass("active");
// get the delay time from the data-delay-time attribute
setTimeout(run, next.data("delayTime"));
}
})();
.active {
background: blue;
color: white
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="outer">
<div class="banner-container" data-delay-time="1000">foo</div>
<div class="banner-container" data-delay-time="2000">bar</div>
<div class="banner-container" data-delay-time="6000">baz</div>
<div class="banner-container" data-delay-time="10000">boo</div>
</div>

Check if text exist in div using jquery

I would like to check if the text exist in the div element, so that if text matches the text in div it will alert "hello". May I know how am I able to achieve this result? Thank you.
<script type="text/javascript">
jQuery(document).ready(function(){
var text = "div[style*=\"width: 550px;\"]";
if (#content.indexOf(text) > -1){
alert("Hello");
}
});
</script>
<div id="content">
<div style="width:550px;">James</div>
<div style="width:500px;">Amy</div>
</div>
Here you go with a solution https://jsfiddle.net/9kLnvyqm/
if($('#content').text().length > 0) { // Checking the text inside a div
// Condition to check the text match
if($('#content').text().indexOf('Amy')){
console.log('Hello');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
<div style="width:550px;">James</div>
<div style="width:500px;">Amy</div>
</div>
If you want only the text content from a container then use text(), if you are looking for html content then use html().
Hope this will help you.
It is possible to get the value of inline style of an element.
var wid = $("#content > div")[0].style.width;
if(wid === "550px"){
//correct width detected. you can use alert instead of console.log
console.log("hello");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
<div style="width:550px;">James</div>
<div style="width:500px;">Amy</div>
</div>
You have multiple elements inside #content. you may want to use the return value of
$('#content').children().length;
and loop the program to get inline width of all elements. Ping if you need some help with the loop

Multiple Summer note divs on one page

I am trying to get the code of a specific summer note div with multiple ones on a single page.
My summer notes are created from a database with php as follows:
<div class="tab-content">
<?php $i=-1; foreach($contents as $content): ?>
<?php $i++; ?>
<div class="tab-pane" id="<?php echo $content->contentName; ?>">
<div class="summernote" data-id="<?php echo $i; ?>">
<?php echo $content->content; ?>
</div>
</div>
<?php endforeach; ?>
</div>
And then my javascript is:
<script>
$('.summernote').summernote({
onblur: function(e) {
var id = $('.summernote').data('id');
var sHTML = $('.summernote').eq(id).code();
alert(sHTML);
}
});
</script>
It always gets the first $('.summernote').eq(0).code(); summernote code never the second or third one.
What I'm trying to do is when each summernote gets a blur, have that code update in a hidden textarea to submit back to the database.
(btw) I am initilizing the summer notes like this:
<script>
$(document).ready(function() {
$('.summernote').summernote({
height: 300,
});
});
</script>
After selecting all summernote's you need to access their attributes by specifying one element like:
<script>
$('.summernote').each(function(i, obj) { $(obj).summernote({
onblur: function(e) {
var id = $(obj).data('id');
var sHTML = $(obj).code();
alert(sHTML);
}
});
});
</script>
To display multiple editors on a page, you need to place more than two <div> elements in HTML.
Example:
<div class="summernote">summernote 1</div>
<div class="summernote">summernote 2</div>
Then run summernote with jQuery selector.
$(document).ready(function() {
$('.summernote').summernote();
});
For more information click
Note: Multiple Editor summernote not work with id
I Finally got the code working for multiple summernote editors and image uploading!
To fix
"undefined"
, try:
var id = $(obj).data('id');
to
var id= $(obj).attr('id'))
Source:
https://github.com/neblina-software/balerocms-enterprise/blob/master/src/main/resources/static/js/app.js
Regards!
For anyone looking to use summernote to output multiple content with foreach, loop/repetitive statement etc
Summernote works for the first output only but you can make it work for others by using the class twice:
<div class"summernote summernote"> </div>
Provided your script is like this:
<script>
$(document).ready(function() {
$('.summernote').summernote();
});
</script>
if you are using summernote inside a textarea in a form and you intend to apply it on multiple textarea(s) on the same form, replace id=summernote with class="summernote"
Dont forget to do the same on your initialisation script
<script>
$('.summernote').summernote({
height: 200 //just specifies the height of the summernote textarea
});
</script>
Example
<textarea class="summernote" name="valueToBeExtractedBackend" required></textarea>
<script>
$('.summernote').summernote({
height: 200
});
</script>

how to hide the slider when clicking somewhere else in body

I have this contact us button sticking to the left of the screen which has a form attached which is hidden by default(because it has negative left of (-472px)).
Now When I click on it left becomes 0px and form slides in(using animate method) with the contact us button itself.
When I click again on the contact us button form and button slides back and hide having left property set to -472 again.
Now I want it also to hide if use click somewhere else on the screen instead of click just the button. I've tried but now its slides in and slides back and hide at the same time.
How can I make it work properly.
code where the problem is: jquery code which is not working is that the bottom of the code like
// clicking somewhere else ------------------------------------------------------------------
jQuery("body").click(function(e){
Full code
<style>
#form_contact_wrapper{position: absolute;top: 225px;left: -472px;z-index: 999;}
#contact-btn-div{top: 267px;float:left;}
#form_contact {z-index: 999;width: 450px;border: 1px solid;border-color: #BBB;padding: 10px;background-color: #FFF;float:left;}
#form_contact p.required{width: 450px;}
</style>
<?php if(Mage::helper('customer')->isLoggedIn() && Mage::app()->getStore()->getCode()=="default"):?>
<div id="form_contact_wrapper">
<div id="form_contact" class="form_contact">
<div id="form_contact_container" class="form_contact_container">
<div class="form_contact_div">
<?php
$filter = new Mage_Widget_Model_Template_Filter();
$_widget = $filter->filter('{{widget type="webforms/form" webform_id="' . Mage::getStoreConfig('webforms/contacts/webform') . '" template="webforms/default.phtml" redirect_url="www.google.com" }}');
echo $_widget;
?>
<a id="contact_new_question_link" href="javascript:void(0)" style="display: none;text-decoration: underline;"><span><span id = "contact_ask_another">Ask another Question</span></span></a>
</div>
</div>
</div>
<div id="contact-btn-div"><img src="<?php echo $this->getSkinUrl('images/contact-us.png'); ?>"></div>
</div>
<script type="text/javascript">
jQuery(function(){
var webform_id = <?php echo Mage::getStoreConfig('webforms/contacts/webform'); ?> ;
var webform_label = jQuery("#webform_"+webform_id+"_form form div ul li div label" );
var webform_fields = jQuery("#webform_"+webform_id+"_form form div ul li div label").next().children();
webform_label.css('width', '100px');
webform_fields.css("width","250px");
// with sucess text
if(jQuery('#form_contact_container .webforms-success-text').length == 1){
jQuery("#form_contact_wrapper").animate({'left': '0px'});
jQuery("#form_contact_wrapper").addClass('active');
jQuery('#form_contact_container .webforms-success-text').show();
jQuery('#form_contact_container .webforms-success-text p').attr('id','success_msg');
jQuery("a#contact_new_question_link").show();
jQuery("a#contact_new_question_link").addClass('active');
jQuery("#webform_"+webform_id+"_form").css({display:'none'});
jQuery("#contact-btn-div").toggle(function(){
jQuery("#form_contact_wrapper").removeClass('active');
jQuery("#form_contact_wrapper").animate({'left': '-472px'});
},function(){
jQuery("#form_contact_wrapper").animate({'left': '0px'});
jQuery("#form_contact_wrapper").addClass('active');
});
if(jQuery("ul.messages").length > 0){
//
jQuery("#feedback_btn_form").after(jQuery("ul.messages"));
}
}
// without success text
if(jQuery('#form_contact_container .webforms-success-text').length == 0){
jQuery("#contact-btn-div").click(function(){
if(jQuery("#form_contact_wrapper").hasClass('active')){
jQuery("#form_contact_wrapper").animate({'left': '-472px'});
jQuery("#form_contact_wrapper").removeClass('active');
}else{
jQuery("#form_contact_wrapper").animate({'left': '0px'});
jQuery("#form_contact_wrapper").addClass('active');
}
});
}
// new question
jQuery("a#contact_new_question_link").click(function(){
// jQuery("#form_contact_wrapper").animate({'left': '-472px'});
jQuery('#form_contact_container .std.webforms-success-text').css({display:'none'});
jQuery(this).hide();
jQuery("#webform_"+webform_id+"_form").show();
});
// clicking somewhere else ------------------------------------------------------------------
jQuery("body").click(function(e){
if(jQuery("#form_contact_wrapper").hasClass('active')){
if(jQuery(e.target).closest('#form_contact').length == 0 && e.target.id != '#contact-btn-div'){
jQuery("#form_contact_wrapper").removeClass('active');
jQuery("#form_contact_wrapper").animate({'left': '-472px'});
}
}
});
});
</script>
<?php endif; ?>
Please suggest something. Thanks a lot.
Use .blur() method. The blur event is sent to an element when it loses focus. An element can lose focus via keyboard commands, such as the Tab key, or by mouse clicks elsewhere on the page. Read more

JS: Hiding DIV based on another DIVs content

I am looking to hide a number of DIVs based upon the specific text of another DIV. My Javascript (below) isn't working.
The HTML:
<div id="LEGEND">abAB</div>
<div id="small-a"></div>
<div id="small-b"></div>
<div id="big-a"></div>
<div id="big-b"></div>
If the LEGEND DIV contains the text a, then I want it to show only DIV small-a.
If the LEGEND DIV contains the text bA, then I want it to show only DIV small-b and big-a.
The Javascript:
<script>
window.onload = function ShowHide{
if (document.getElementById('LEGEND').indexOf("a") > 0){
document.getElementById('small-a').style.display = 'block';}
if (document.getElementById('LEGEND').indexOf("b") > 0){
document.getElementById('small-b').style.display = 'block';}
if (document.getElementById('LEGEND').indexOf("A") > 0){
document.getElementById('big-a').style.display = 'block';}
if (document.getElementById('LEGEND').indexOf("a") > 0){
document.getElementById('big-b').style.display = 'block';}
</script>
You are forgetting a couple of things.
A function declaration should be like this
function functionName(args) {
}
You have to hide the divs using style.display = "none"
Example:
<div id="LEGEND">abB</div>
<div id="small-a" style="display: none;">This is small-a</div>
<div id="small-b" style="display: none;">This is small-b</div>
<div id="big-a" style="display: none;">This is big-a</div>
<div id="big-b" style="display: none;">This is big-b</div>
<script>
function showElement(id) {
document.getElementById(id).style.display = "block";
}
window.onload = function ShowHide() {
var legend = document.getElementById("LEGEND").innerHTML;
if(legend.indexOf("a") != -1) showElement("small-a");
if(legend.indexOf("b") != -1) showElement("small-b");
if(legend.indexOf("A") != -1) showElement("big-a");
if(legend.indexOf("B") != -1) showElement("big-b");
}
</script>
The problem is that your code changes the other div elements to block-level elements when div is already a block-level element. You need to set them not to display initially using CSS and then reveal them in the JavaScript.
Try this instead:
<div id="LEGEND">abAB</div>
<div id="small-a" style="display: none;"></div>
<div id="small-b" style="display: none;"></div>
<div id="big-a" style="display: none;"></div>
<div id="big-b" style="display: none;"></div>
<script type="text/javascript">
window.onload = function() {
if (document.getElementById('LEGEND').indexOf('a') > 0) {
document.getElementById('small-a').style.display = 'block';
...
// etc.
}
}
</script>
First, try making sure the window.onload is being called:
window.addEventListener('load', ShowHide, false);
function ShowHide()
{...
Second, you should be looking at the InnerHTML of the element:
if (document.getElementById('LEGEND').innerHTML.match("a") == "a"){...
Third, each if statement should also contain an else (replace divName with real div names):
else {
document.getElementById('divName').style.display = 'none'}
Hope that helps!
~md5sum~
EDIT:
Also, I'm not 100% sure on this, but I believe that the syntax:
window.onload = function ShowHide{
will completely fail. I think that the syntax should be:
window.onload = function(){
If me, I will do like this. you dont need to touch HTML part, everything is done in javascript.
you can extend it to CDEFGH...
and you don't need to set <div id="small-X" style="display: none;"> for each tags too. :-)
<body>
<script>
window.onload=function(){
x=document.getElementsByTagName("div");
//first hide everything with small- or big-
for(i in x)
if(/small-|big-/.test(x[i].id))
x[i].style.display="none";
//then turn on each tags based on LEGEND
x= document.getElementById("LEGEND").innerHTML;
for(i=0;i<x.length;i++)
document.getElementById((x[i]<='Z'?'big-':'small-')+x[i].toLowerCase()).style.display='block';
}
</script>
<div id="LEGEND">aAB</div>
<div id="small-a">a</div>
<div id="small-b">b</div>
<div id="big-a">A</div>
<div id="big-b">B</div>
</body>
You need to set the style.display property to none.

Categories