JQuery append elements are going out of parent div width? - javascript

I have a html div which is styled using bootstrap class span9.
<div class="span9">
<div id = "selectedtags" class="well">
</div>
<button class="btn" type="button" id="delegatecontent">Create report</button>
</div>
What i am trying to achieve is, write a jquery click event on following li tags (20+ li tags in actual ) and append the newly created element inside the #selectedtags div.
<li class="dbcol">Location_Id</li>
<li class="dbcol">Location_Name</li>
<li class="dbcol">Location_EN</li>
Following is my javascript (Jquery) code to append span tags inside the #selectedtags div.
$(document).ready(function() {
$('.dbcol').live('click', function () {
var str = "";
str = $(this).closest("ul").attr("id");
var master_name = "";
if (str == "countryselect") {master_name = "Country_Master"}
if (str == "stateselect") {master_name = "State_Master"}
if (str == "locationselect") {master_name = "Location_Master"}
if (str == "hotelselect") {master_name = "Hotel_Master"}
var $newelement = "";
$newelement += '<span class="label label-info isr" style="margin-top:3px; margin-bottom:2px; margin-right:5px; margin-left:3px; padding:2px;" id = ' +str+ '>';
$newelement += master_name + '.';
$newelement += $(this).text() + " ";
$newelement += '<i class="icon-remove icon-white"></i>';
$newelement += '</span>';
$(this).remove();
$("#selectedtags").append($newelement);
});
$("i").hover(
function () {
$(this).removeClass('icon-white');
});
$('i').live('click',function() {
var id = '#'
id += $(this).closest("span").attr("id");
var trt = $(this).closest("span").text();
trt = trt.substring(trt.indexOf('.')+1);
$(id).append('<li class="dbcol">' + trt +'</li>');
$(this).closest("span").remove();
});
$("#delegatecontent").live('click',function() {
var strqw ="";
var final_string = "Select ";
$('.isr').each( function() {
var df = $(this).text();
if (strqw == ""){
strqw += df;
}
else
{
strqw += ', ';
strqw += df;
}
});
final_string += strqw;
alert (final_string);
});
});
Everything works fine, Jquery code do append the newly created span tags in the div however the new tags goes out of the div width (span9) instead of going in the next line.
In addition to the default bootstrap style, following is added:
body {padding-top: 40px; padding-bottom: 40px; font-family: 'Monda', sans-serif;}
ul li {cursor: pointer;}
Help Please. Thanks

class label label-info is causing the issue here.
$newelement += '<span class="label label-info isr" style="margin-top:3px; margin-bottom:2px; margin-right:5px; margin-left:3px; padding:2px;" id = ' +str+ '>';
$newelement += master_name + '.';
$newelement += $(this).text() + " ";
$newelement += '<i class="icon-remove icon-white"></i>';
$newelement += '</span>';
I am using the bootstrap class "label label-info" to style the newly created span tags.
If i remove the class label label-info the code works fine.
$newelement += '<span class="isr" style="margin-top:3px; margin-bottom:2px; margin-right:5px; margin-left:3px; padding:2px;" id = ' +str+ '>';
$newelement += master_name + '.';
$newelement += $(this).text() + " ";
$newelement += '<i class="icon-remove icon-white"></i>';
$newelement += '</span>';
I am using a custom style now for span tags.
Thanks for help.

Try overflow:hidden style on "selectedtags" div.
ie
<div class="span9">
<div id = "selectedtags" class="well" style='overflow:hidden'>
</div>
<button class="btn" type="button" id="delegatecontent">Create report</button>
</div>

Related

Unable to display JavaScript / jQuery div tag without dependency on another tag

I'm using JavaScript with jQuery to display my RSS Medium feed when there is a <div id="medium-feed"... on the page.
When the JSON data is pulled, I display the data using HTML, some CSS, and the bootstrap library with day.js (to format the date). So far it worked as expected (see code snippets at the bottom).
I also want to display a more compact version of the feed to my footer that shows the title and published date. So I copied down my original code and have JavaScript look for a <div id="medium-feed-footer"... to display the other version of the feed so it can look like this:
This only works if I show both of my div elements on the same page, like my blog page:
<div id="medium-feed" username="factmaven" read-more="Read More"></div>
<div id="medium-feed-feed" username="factmaven"></div>
But if I visit any other page that only shows the footer version of my feed, it's empty, as seen on my homepage. When you test out my code snippet, just add the -footer part in the ID on its own and it won't show up. It looks like there is a dependency to show both div tags in order for it to work properly.
How can I have my footer version show up independently? I tried various ways such as breaking this code into two separate files and trying an if/then statement, but the result is always the same.
$(document).ready(function() {
// Get option values
var divID = 'medium-feed';
var mediumUsername = document.getElementById(divID).getAttribute('username');
var readMore = document.getElementById(divID).getAttribute('read-more');
/* Medium Feed */
document.getElementById(divID).innerHTML =
($.getJSON('https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/' + mediumUsername,
function(json) {
$('#' + divID).html('');
// For loop each Medium post in HTML structure
for (var i in json.items) {
// Define custom value with regex and replace
var thumbnail = json.items[i].thumbnail.replace(/max\/(.+?)\//g.exec(json.items[i].thumbnail)[1], $('#' + divID).width());
var subtitle = /<p class="medium-feed-snippet">(.+?)<\/p>/g.exec(json.items[i].description)[1];
var pubDate = dayjs(json.items[i].pubDate).format('MMM D, YYYY');
var categories = json.items[i].categories.join(', #');
// HTML post structure
$('#' + divID).append(
'<div class="blog-post col-lg-4 col-md-6 col-sm-12">' +
'<div class="blog-post-date">' + pubDate + '</div>' +
'' +
'<a href="' + json.items[i].link + '" target="_blank" ' + 'title="' + json.items[i].title + '">' +
'<h3>' + json.items[i].title + '</h3>' +
'</a>' +
'<small>by ' + json.items[i].author + '</small>' +
'<hr>' +
'<p>' + subtitle + '.</p>' +
'<small>#' + categories + '</small>' +
'<p>' + readMore + ' <i class="fas fa-long-arrow-alt-right"></i></p>' +
'</div>'
);
}
}));
/* Footer Medium Feed */
document.getElementById(divID + '-footer').innerHTML =
($.getJSON('https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/' + mediumUsername,
function(json) {
$('#' + divID + '-footer').html('');
// For loop each Medium post in HTML structure
for (var i in json.items.slice(0, 5)) {
var pubDate = dayjs(json.items[i].pubDate).format('MMM D, YYYY');
// HTML post structure
$('#' + divID + '-footer').append(
'<a href="' + json.items[i].link + '" target="_blank" ' + 'title="' + json.items[i].title + '">' +
'<h4>' + pubDate + '</h4>' +
'<h5>' + json.items[i].title + '</h5>' +
'</a>'
);
}
}));
});
.blog-post-image {
width: 100%;
background-repeat: no-repeat;
background-position: 50%;
background-size: cover;
overflow: auto;
display: block;
}
.blog-post-image:after {
content: "";
display: block;
position: relative;
margin-top: 60%;
width: 100%;
z-index: 1;
}
.blog-post-date {
position: absolute;
background-color: #ffffff;
padding: 5px;
color: #000000;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.9.6/dayjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-offset-1 col-md-10 col-sm-12">
<div class="section-title">
<h3>Latest Blog Posts</h3>
</div>
<div id="medium-feed" username="factmaven" read-more="Read More"></div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/js/bootstrap.min.js"></script>
On other pages, Javascript doesn't find an element with id = "medium-feed" so it returns an error. First, check if the element exists.
$(document).ready(function() {
// Get option values
var divID = 'medium-feed';
var mediumUsername = document.getElementById(divID).getAttribute('username');
var readMore = document.getElementById(divID).getAttribute('read-more');
/* Medium Feed */
var divContainer = document.getElementById(divID);
if (divContainer) {//check if element exists
divContainer.innerHTML = ($.getJSON('https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/' + mediumUsername,
function(json) {
//rest of your code
}))
}
})

How to change the color of a string before inserting it at the current position of the cursor

I get this output while trying to change the color of the string I would like to add in my editor.
The css part is not taken into account. It is added as a simple html. What could be the problem ?
some text <font color="green">ADD THIS VALUE</font> some text and ...
Here are the add functions
function add_str(event) {
event.preventDefault()
var elt = document.getElementById("text_write");
insertAtCursor(elt, "ADD THIS VALUE");
}
function insertAtCursor(myField, myValue) {
myValue = myValue.fontcolor("green");
if (myField.setRangeText) {
myField.setRangeText(myValue)
} else {
document.execCommand('insertText', false, myValue);
}
}
and the html part
<button onmousedown="add_str(event)">
add srting
</button>
<div contenteditable="true" id="text_write" style="height:200px; width:500px; border:2px solid black;">some text some text and ...</div>
Thank you in advance
function add_str(event) {
event.preventDefault()
var coloredstring = "ADD THIS VALUE"
var colorofstring = "green"
var node = document.getElementById("text_write")
var addedstring = '<span style="color:' + colorofstring + '">' + coloredstring + '</span>'
node.innerHTML = node.innerHTML + addedstring
}
<button onmousedown="add_str(event)">
add srting
</button>
<div contenteditable="true" id="text_write" style="height:200px; width:500px; border:2px solid black;">some text some text and ..</div>
font tag no longer works on html5, i did a little hack using a span tag

How can I use bind and unbind with this?

I have two click functions, one function is for adding vacation in a list, the other function is for removing vacation from the list. When I add vacation to the list, I don't want to be able to click on that specific button again .ledig-btn. If I remove a specific vacation from the list, then I want to be able to click that .ledig-btn again. I have tried with jQuery(this).off('click'); and Its working, but then when I remove vacation from the list I want to add the click event again.
jQuery(".ledig-btn").on('click', function(event) {
var id = jQuery(this).attr('id');
jQuery(this).unbind("click");
jQuery('.minlista').append('<tr><td><div class="list-domains" data-id='+id+'><span class="delete-list-domains">X</span>' + '<td class="tld-sok">' + searchWord + '<div class="tld-sok-ilista">' + domain + '</div>' + '</td>' + '</div></td></tr>');
event.stopImmediatePropagation();
jQuery("tr td .list-domains").on('click', function(e) {
var delRow = jQuery(e.target).closest('tr');
delRow.remove();
});
});
According to your script, you're storing the button id as a data-attribute called data-id, so we can use it as follow:
function myClickHandler(event) {
var id = $(this).attr('id');
$(this).off("click");
// +--- Data attribute with the
// | related 'ledig-btn'
// v
$('.minlista').append('<tr><td><div class="list-domains" data-id='+id+'><span class="delete-list-domains">X</span>' + '<td class="tld-sok">' + searchWord + '<div class="tld-sok-ilista">' + domain + '</div>' + '</td>' + '</div></td></tr>');
event.stopImmediatePropagation();
$("tr td .list-domains").on('click', function(e) {
var ledigBtnId = $(this).data('id'); // ledig-btn ID
var delRow = $(e.target).closest('tr');
delRow.remove();
// Here we re-bind the click event handler.
$("#" + ledigBtnId).on("click", myClickHandler);
});
}
$(".ledig-btn").on('click', myClickHandler);
Instead of adding/removing the click event on items, you could register a single handler onto a common ancestor using event delegation, then just check the clicked item hasn't already been added to the 2nd list, with the help of the id attribute and the data-id you use.
Here is a simplified demo:
jQuery("#available").on('click', '.ledig-btn', function(event) {
var btn = jQuery(this), item = btn.closest('div'), id = item.attr('id');
if ($('#added').find('[data-id="'+id+'"]').length){
alert('Item already added to the list.');
return;
}
jQuery('.minlista').append(`
<tr>
<td>
<div class="list-domains" data-id=`+id+`>
<span class="delete-list-domains">×</span>
</div>
</td><td class="tld-sok">` + item.text().replace('Add','')
+ '<div class="tld-sok-ilista">Some dynamic content</div></td></tr>'
).find(".list-domains").last().on('click', function(e) {
jQuery(e.target).off('click').closest('tr').remove();
});
event.stopImmediatePropagation();
});
#available, #added{float:left; width:50%; box-sizing: border-box; border: 1px solid black;
margin: 2px; min-height: 10px}
#available div{clear:both; vertical-align: middle}
#available button{float: right}
.delete-list-domains{cursor: pointer; padding:2px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
</p>
<div id="available">
<div id="v1" class="vacation">Vacation 1<button class="ledig-btn">Add</button></div>
<div id="v2" class="vacation">Vacation 2<button class="ledig-btn">Add</button></div>
<div id="v3" class="vacation">Vacation 3<button class="ledig-btn">Add</button></div>
</div>
<div id="added">
<table><tbody class="minlista">
</tbody></table>
</div>

auto refresh json without reload

i am trying to make an auto refresh json which is reloading for changes every 5 seconds. It loads perfectly first time on load but my setinterval is not working correctly. It goes of every 5 seconds but it doesnt update my menu even though changes has been made? .
Here is what i got so far:
$(document).ready(function(load) {
var dmJSON = "example.com";
$.getJSON( dmJSON, function(data) {
setInterval(function () {
$(news).html("");
$.getJSON();
}, 5000);
var html = '';
// loop through all the news items, and append the
// title and published date to the html variable.
for(var i = 0; i < data.feed.data.length; i++){
html += '<div style="width: 600;direction: rtl;background-color: white;padding: 12px 12px 0;border: 1px solid;border-color: #e5e6e9 #dfe0e4 #d0d1d5;border-radius: 4px;margin-bottom: 20px;color: black;">';
html += '<span style="/* text-align: left; */direction: rtl;position: absolute;left: 250px;"> ' + data.feed.data[i].created_time + ' </span><span><img alt="" src="http://icons.iconarchive.com/icons/gakuseisean/ivista-2/128/Network-Globe-Disconnected-icon.png" style="background-size:auto;background-repeat: no-repeat;display: inline-block;height: 20px;width: 20px;position: absolute;left: 490px;padding-top: 9px;" /></span>' ;
html += '<br>' ;
html += data.feed.data[i].message ;
html += '<p><img alt="" src=' + data.feed.data[i].picture + ' /></p>';
html += '</div>';
}
// append all the html variable to the ticker div.
$("#news").append(html);
});
});
i use this code but when refresh he give my empty page
setInterval(function () {
$(news).html("");
$.getJSON();
}, 5000);
Try this:
$(document).ready(function(load) {
var dmJSON = "https://";
function fetch() {
$.getJSON( dmJSON + (+new Date()), function(data) {
$("#news").html('');
var html = '';
// loop through all the news items, and append the
// title and published date to the html variable.
for(var i = 0; i < data.feed.data.length; i++){
html += '<div style="width: 600;direction: rtl;background-color: white;padding: 12px 12px 0;border: 1px solid;border-color: #e5e6e9 #dfe0e4 #d0d1d5;border-radius: 4px;margin-bottom: 20px;color: black;">';
html += '<span style="/* text-align: left; */direction: rtl;position: absolute;left: 250px;"> ' + data.feed.data[i].created_time + ' </span><span><img alt="" src="http://icons.iconarchive.com/icons/gakuseisean/ivista-2/128/Network-Globe-Disconnected-icon.png" style="background-size:auto;background-repeat: no-repeat;display: inline-block;height: 20px;width: 20px;position: absolute;left: 490px;padding-top: 9px;" /></span>' ;
html += '<br>' ;
html += data.feed.data[i].message ;
html += '<p><img alt="" src=' + data.feed.data[i].picture + ' /></p>';
html += '</div>';
}
// append all the html variable to the ticker div.
$("#news").append(html);
});
}
setInterval(fetch, 5000);// call fetch every 5 seconds
fetch(); // call fetch first time
});

Adding dynamic styles with conditions to the dom elements

I am generating divs dynamically but What I want is to add a anchor tag that shows a trash image for deleting that particular message on hover of a particular div. I have written a :hover on class to add background and that is working fine but I want to add an anchor tag also . Here is my code::
Style
<style>
.mail:hover {
background-color: #cde6f7;
/*background-image: url("/Content/images/Trash.png");*/
}
.mail {
float: left;
width: 100%;
border-bottom: solid 1px #ccc;
padding-bottom: 10px;
margin-top: 3px;
cursor: pointer;
}
</style>
Here I am creating the dynamic div's and I want to add background color and an trash image image to everydiv I hover
<script>
success: function (data) {
if (data.MessageData != null) {
var DataDiv = "";
for (var iRow = 0; iRow < data.MessageData.length; iRow++) {
var RowData = data.MessageData[iRow];
var date = new Date(parseInt(RowData.Sent_Date.substr(6)));
var style = '';
if (RowData.IsReceiver_Received == false) {
style = 'color:#0460C7' + '!important ';
}
DataDiv += "<div class='mail' id='" + RowData.pkMessageId + "' onclick=ShowMessage('" + RowData.pkMessageId + "')>";
DataDiv += "<h3 style=" + style + ">" + RowData.Subject + "</h3>";
//<label class='label' style='color:red ! important;'> hi hi hi </label>
DataDiv += "<label style=" + style + "class='clsLbl'> From:" + RowData.Message_From + "</label>";
DataDiv += "<label style=" + style + "class='clsLb2'>" + date.toDateString() + "</label></div>";
}
$("#hdnSearchType").val(1);
$("#hdnUserType").val(1);
}
$("#MessageStore").html('');
$("#MessageStore").html(DataDiv);
},
</script>
$(".mail").live('hover', function(e){
$("#"+this.id).append("<a>addd</a>");
});
If I understand your question properly, you would need to do this:
While dynamically creating the <div>'s HTML, also add this inside the div:
DataDiv += "<a href='its-url' class='trash'></a>";
This will add an anchor inside your dynamic elements.
Since you want to keep this hidden and it will be only visible when you hover over the "mail" div,
.trash { display: none; }
.mail:hover .trash { display: block; }
Will work for you.
You can then use background-image or <img src=""> to show the trash icon inside this anchor element.

Categories