I have this line of javascript which creates a listing of store locations, and creates a DIV beneath the map. The items are displayed on the page top to bottom.
I would like to display the items as 3 in a row, left to right, top to bottom.
The function is this:
function createSidebarEntry(marker, name, address, city, state, zipcode, telephone, images, url) {
var div = document.createElement('div');
var html = "<p><a href='http://" + url + "'>" + name + "</a><br/>" + address + "<br/>" + city + ", " + state + " " + zipcode + "<br/>" + (formatPhone(telephone)) + "</p>";
div.innerHTML = html;
div.style.marginBottom = '5px';
return div;
}
As a side bar question, would tables be the preferred method?
I have tried to set the DIV as:
#sidebar {
text-align: left;
margin: 0px auto;
padding: 0px;
border:0;
width:665px;
font-size:10pt;
font-family:Arial;
color:#656668;
display: table-cell;
}
And unfortunately after working with margins, etc, I have seemed to run out of luck. Has anyone been able to use dynamic returned data and apply formatting with CSS in three columns? I have been googling and everything I see points me to creating three column styles within my DIV container.
try setting the parent element with a fixed width and apply float to the childs and a width of 33% for them. Don't forget to use a clear afterwards.
I would suggest creating your elements with jquery. It's alot easier and more elegant.
But the root of you issue is that you need to add a float:left; style to your div. This will put all your divs in the same row.
Oh, and try to use tables as little as possible to layout out elements on your page. Divs and CSS are the way to go.
Related
This question already has answers here:
How to change content of div on hover using JQuery/Javascript
(6 answers)
Closed 3 years ago.
I have a link inside a div. Inside the link (between the ), I have text displayed. I want to change that text when the cursor hovers over the link.
***One thing I forgot to mention is that I want the text to be temporarily changed (i.e. only when it's hovered over).
Here's my JSFiddle: https://jsfiddle.net/ZEZEME/kapt4sL6/5/
This is what my code looks like.
HTML
<div id="imgDiv"></div>
CSS
#imgDiv {
width: 200px;
height:200px;
background-color: gray;
}
JS
var title = "World War II Plane Crashes in National Parks";
var url = "https://www.nps.gov/articles/WWIIPlaneCrashes.htm"
$(imgDiv).append($('<a href="' + url + '" id=link>'+ title +'</a>'));
(I'm working with APIs, and .append is how I create the links. I need to dynamically create them to the div in JavaScript).
This is what I've tried:
$(imgDiv).append($('<a href="' + url + '" id=link>'+ title +'</a>').css('text-decoration', 'none').hover(function(e) {
console.log($(e.target).text("NEWWW"));
}));
This permanently changes the text (as opposed to only when hovered over).
$(imgDiv).append($('<a href="' + url + '" id=link>'+ title +'</a>').css('text-decoration', 'none').hover(function(e) {
function(e) {
console.log($(e.target).text("NEWWW"));
},
function(e) {
console.log($(e.target).text("OLDDD"));
}
This gives me an error. Can anyone help?
You can use mouseover to detect when the mouse moves over the link, you can then use mouseout to see when it leaves the link.
You also want to use text() as val() is for form fields.
var title = "World War II Plane Crashes in National Parks";
var url = "https://www.nps.gov/articles/WWIIPlaneCrashes.htm"
$('#imgDiv').append($('<a href="' + url + '" id=link>'+ title +'</a>'))
// Create an event to watch "a" tags
$('#imgDiv a').on('mouseover', (e) => {
$(e.target).text('I am some new text')
})
// Comment this out if you don't want it to go back on mouse out.
.on('mouseout', (e) => {
$(e.target).text(title)
});
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#imgDiv {
width: 200px;
height:200px;
background-color: gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgDiv"></div>
On my webpage there are Gridster widgets.In these widgets initially the images are displayed from JSON(the name of image comes from JSON which I then put in src of image)
The users can also add images by clicking + button.User can also delete an image by clicking X button on the image.
The Problem I am facing
When the images coming from JSON are more or when the user manually adds more images then the images go out of widgets.
My Desired Output
Now I was trying to restrict those images in widget such that images will lay only in boundaries of div.
When there are more images the other existing images will resize and all of the images will fit in that area.
When I delete an image the other images will get bigger.In any case the entire area will be occupied by the images.
JS:
//JSON which I get from backend
var json = [{
"html": "https://d30y9cdsu7xlg0.cloudfront.net/png/802768-200.png,https://d30y9cdsu7xlg0.cloudfront.net/png/802768-200.png,https://d30y9cdsu7xlg0.cloudfront.net/png/802768-200.png", //3 Images
"col": 1,
"row": 1,
"size_y": 2,
"size_x": 2
}
];
//Loop which runs over JSON to generate <li> elements in HTML
for (var index = 0; index < json.length; index++) {
var images = json[index].html.split(',');
var imageOutput = "";
for (var j = 0; j < images.length; j++) {
imageOutput += '<div class="imagewrap"><img src=' + images[j] + '> <input type="button" class="removediv" value="X" /></div></div>';
}
gridster.add_widget('<li class="new" ><button class="addmorebrands" style="float: left;">+</button><button class="delete-widget-button" style="float: right;">-</button>' + imageOutput + '<textarea>' + json[index].html + '</textarea></li>', json[index].size_x, json[index].size_y, json[index].col, json[index].row);
}
//Function to delete an image from widget
$(document).on('click', '.removediv', function() {
$(this).closest('div.imagewrap').siblings('textarea')
$(this).closest('div.imagewrap').remove();
});
//Function to delete a widget
$(document).on("click", ".delete-widget-button", function() {
var gridster = $(".gridster ul").gridster().data('gridster');
gridster.remove_widget($(this).parent());
});
//Function to add mode Images to widgets from Modal
var parentLI;
$(document).on("click", ".addmorebrands", function() {
parentLI = $(this).closest('li');
$('#exampleModalCenter').modal('show');
$('#exampleModalCenter img').click(function() {
$(this).addClass('preselect');
$(this).siblings().removeClass('preselect');
selectedImageSRC = $(this).attr('src');
})
});
$('#add-image').click(function() {
parentLI.append('<div class="imagewrap"><img src="' + selectedImageSRC + '"> <input type="button" class="removediv" value="X" /></div>');
parentLI.children('textarea').append(', ' + selectedImageSRC);
$('#exampleModalCenter').modal('hide');
})
HTML
<div class="gridster">
<!-- <li> from JSON are placed here images are a part of li -->
<ul>
</ul>
</div>
The Fiddle so far
I am not sure if this can achieved just with CSS or will require any JS along with that
Update 1
I have tried with a lot of different CSS but still not able to get the expected output so if someone can help me with it would be really helpful
Maybe Gridster has a built in way to arrange items inside the grid cells, in case you have not found a way yet, try this.
I added some css:
.image-wrap-container{
min-height: 70%
}
.image-wrap-container div.imagewrap{
width: 33%
}
.text-area-wrap{
bottom: 0px;
left: 0px;
margin: 0px;
padding: 0px;
width: 100%;
height: 30%;
display: inline-flex;
}
.new.gs-w{
width: 200px;
min-height: 200px
}
.addmorebrands{
position: absolute;
left:0
}
.delete-widget-button{
position: absolute;
right:0
}
and restructured a little bit your html so images fit good within the cell, I hope that does not break anything, javascript was the least modified, only to add the images according to the new html structure.
Note: I tried to make the lis' height adjust to the amount of elements it contains, but [data-sizey="2"] kept getting in my way, so before throwing some probably unnecessary hack on it, try and achieve that using the library's own options, good luck.
Also, I noticed you were using this to update your textareas:
parentLI.children('.imagenames').val(function(i, selectedImageSRC) {return selectedImageSRC + ', '});
which won't work because you are using the same name for the argument, conflicting with the original selectedImageSRC variable. In case you are still having problems in that front, I replaced it with:
parentLI.children('.imagenames').val(function(i, currentContent) {return currentContent + ',' + selectedImageSRC + ', '});
Bonus Feature
The buttons for removing an image were to big for the images and covered quite a big part, so I took the liberty:
.removediv{
visibility: hidden
}
.imagewrap:hover .removediv{
visibility: visible
}
hope it helps
I have a div that act as a console. It record the activity on the site. I display message in it and to apply color to the text I use <span> elements with CSS classes.
My CSS classes
.consoleError{ <---- dynamic prepend
color: #f00;
}
.consoleGood{ <---- dynamic prepend
color: #2aff01;
}
The JavaScript that prepend(Jquery) the stings:
$('#console').prepend('<span class="consoleError">ERREUR : </span>' + data[i] + '<br>');
}
$('#console').prepend('<span class="consoleGood"> Status: ' + data[0] + '</span> Requête: ' + action + ' Conteneur:' +container+ '<br>');
I use prepend to insert them at the top;
Now the problem is that when an error occur the "consoleError" class is taking effect I see it live in red;
The other class "consoleGood" spans are inserted before I can actually view them because of the time it take me to get to the console.
So I'm wondering why one span CSS is working and not the other that was inserted prior to activating the display of "#console" element?
Anyone know what is wrong here?
CSS
.page{
width: 275px;
hight: 380px;
overflow: auto;
}
HTML
<div class="page">dynamic text</div>
How to create a new div when the dynamic text is overflowing past the fixed height of the div?
Example:
<div class="page">Some dynamic texts will appear here</div>
When the dynamic text is overflowing past the fixed height of the div, the content above will be appear like this.
<div class="page">Some dynamic</div>
<div class="page">texts will</div>
<div class="page">appear here</div>
I've tried using wordwrap function in PHP wordwrap($dynamic_text, 600, '</div><div class="page">'); it's can running, but it had a problem when the character was copied from Ms.Words.
So, by detecting the overflowing text, cut it, and then paste it into the new div element is the better solustion, i guess. But, I don't know how to do this solution using JQuery or Javascript.
Any ideas? Thanks in advance!
You can do it, and it's way more than just a couple lines of code. It took a very experienced developer a couple days. Sorry, can't share the code.
Javascript: Put the whole content into the div. You may keep it hidden or out of the DOM for a while. Traverse the div's children. Find the one whose top+scrollHeight exceeds the div's height. Traverse it recursively. Eventually, you will either find an indivisible element, e.g., an image, that doesn't fit, or a position within a text node to split the text at. Remove that part and all further elements from the div. Add them to a new one.
There are a lot of details to address, so it's not simple. But doable.
I just had something similar working today while I was searching for an answer but there doesn't seem to be anything straight forward.
Although I am using Array.reduce() you should be able to do this with Array.forEach() or any other iterating code you like.
words.reduce(function(acc, value)
This is done by calculating if the element will overflow if we add another word to it before we actually render it. The hacky thing here is to add another block element inside of it with visibility: hidden.
element.innerHTML = '<div style="visibility: hidden; height: 100%; width=100%">' + textToBeAdded + '</div>';
That way the block element still takes its parents dimensions and the parent element can be checked for overflow.
The way to check for overflow is to compare the element's scrolling height to its height:
if (element.scrollHeight > element.offsetHeight)
If it overflows we leave it as is and create a new element and put the current value (word) in the iteration. Then we attach it to the same DOM tree as the previous element (as its parent's child... like having a new brother 😜)
var newPageEl = document.createElement('div');
newPageEl.classList = 'page';
newPageEl.textContent = word;
parentElement.appendChild(newPageEl);
Hope this makes sense.
var page = document.getElementsByClassName('page')[0];
if (page.scrollHeight > page.offsetHeight) {
// is overflowing
fixOverflow(page);
}
function fixOverflow(element) {
var words = element.textContent.split(' ');
// delete previous text content
element.textContent = '';
words.reduce(function(acc, value) {
// store current element's text
var currentElementText = element.textContent.toString().trim();
var textToBeAdded = currentElementText + ' ' + value;
element.innerHTML = '<div style="visibility: hidden; height: 100%; width=100%">' + textToBeAdded + '</div>';
if (element.scrollHeight > element.offsetHeight) {
// is overflowing with the new word
element.innerHTML = "";
// leave the last page element as is
element.textContent = currentElementText;
// create another element with the new value to be added
// ** IMPORTANT replace the memory of the previous element variable
element = createPageElement(value);
// add it to the same DOM tree as the previous page element
page.parentElement.appendChild(element); // could also be document.getElementById('page-container').appendChild(element);
} else {
// if not overflowing add another word
element.innerHTML = currentElementText + ' ' + value;
}
}, "");
}
function createPageElement(text) {
// create element with class page
var newPageEl = document.createElement('div');
newPageEl.classList = 'page';
newPageEl.textContent = text;
return newPageEl;
}
I am working om a menu bar, each menu bar item is an image, when user places mouse over menu item a div with submenu will appear.
I want to place div directly under the appropriate image item (no space, and div will hover above all elements), with right side alignment, meaning the right top corner of div should be under bottom right corner of image.
Because I can't and don't want to hard code position of divs, i want to do it dynamically.
For now I have this:
$('img').each(function(){
jQuery(this).mouseenter(function(){
var menuItem = $('#' + this.id + '_menu'); //get the needed div
var imgRight = this.offset() + this.width();
});
});
The offset() method has top and left properties, you need use them, example:
var imgRight = this.offset().left + this.width();
var imgTop = this.offset().top + this.height();
After that, you will have to give the absolute positioning to the DIVs to place them below the images:
menuItem.css({
position:'absolute',
top: imgTop,
left: imgLeft,
zIndex:5000
});
So your code becomes:
$('img').each(function(){
jQuery(this).mouseenter(function(){
var menuItem = $('#' + this.id + '_menu'); //get the needed div
var imgRight = this.offset().left + this.width();
var imgTop = this.offset().top + this.height();
menuItem.css({
position:'absolute',
top: imgTop,
left: imgLeft,
zIndex:5000
});
// now show the corresponding div
menuItem.show('slow');
});
});
More Info:
http://api.jquery.com/offset/
You shouldn't have to hard code or calculate the position of these items. Any of the following CSS rules should achieve your goal: position: relative; right: 0 or float: right:.
It'd be good to see some of your markup for additional testing. www.jsfiddle.net is a great resource for this.
There are 2 ways to do this: the correct-way or the cheat way...
The correct way: you need to get the top and client height of the actuating object - client heights no prob just call it - but the top means you must get the to of all the parent objects too - use this:
function J_pos(o)
{
var x,y;
y=o.offsetTop;
x=o.offsetLeft;
o=o.offsetParent;
while(o)
{
y+=o.offsetTop;
x+=o.offsetLeft;
o=o.offsetParent;
}
return [x,y];
};
Now the top and client height you do this:
<div style=top:"+(p[0]+obj.clientHeight)+";left:"+p[1]>
The cheat-way (not so dynamic - but quick):
put a tag like a <span> around the actuating (mouseover) object. Make it position-relative. Place a <div> inside it:
<div id="ABC" style="position:absolute;left:0;display:none">
Now on mouseover put document.getElementById("ABC").style.display="" and bottom:0 — boom baby dusted. Downside to this is you have to manually do it for each instance, but if you only have 3 or so well bingo.