How to avoid the text cross the div element in JQuery? - javascript

When I add the card to the in box. Then it is possible to double click on the card, and dialog pop up. In the dialog it is possible to create dynamic checkBoxes.
The issue is when I write some text, the text cross the div element. I don't want that. How can I avoid that?
You can see the problem in the image below:
JQuery:
$(function () {
// Click function to add a card
var $div = $('<div />').addClass('sortable-div');
var cnt = 0,
$currentTarget;
$('#AddCardBtn').click(function () {
var $newDiv = $div.clone(true);
cnt++;
$newDiv.prop("id", "div" + cnt);
$newDiv.data('checkboxes', []);
$('#userAddedCard').append($newDiv);
// alert($('#userAddedCard').find("div.sortable-div").length);
});
// Double click to open Modal Dialog Window
$('#userAddedCard').dblclick(function (e) {
$currentTarget = $(e.target);
$('#modalDialog').dialog({
modal: true,
height: 600,
width: 500,
position: 'center'
});
return false;
});
$("#Getbtn").on("click", function () {
$('#modalDialog').dialog("close");
});
// Add a new checkBox
$('#btnSaveCheckBox').click(function () {
addCheckbox($('#checkBoxName').val());
$('#checkBoxName').val("");
});
function addCheckbox(name, status) {
status = status || false;
var container = $('#boxs');
var inputs = container.find('input');
var id = inputs.length + 1;
var data = {
status: status,
name: name
};
var div = $('<div />', { class: 'allcheckbox' });
$('<input />', {
type: 'checkbox',
id: 'cb' + id,
value: name
}).prop('checked', status).on('change', function () {
data.status = $(this).prop('checked');
}).appendTo(div); /* set checkbox status and monitor changes */
$('<label />', {
'for': 'cb' + id,
text: name
}).appendTo(div);
div.appendTo(container);
}
});
Live Demo

Check these answers:
word-wrap does not work in IE
word-wrap:break-word not working in IE8
Basically you do:
div.break_word {
width: 690px; /* whatever width, if needed */
word-wrap: break-word;
-ms-word-wrap: break-word;
word-break: break-all;
white-space: normal;
}
Related:
http://css-tricks.com/snippets/css/prevent-long-urls-from-breaking-out-of-container/

Either you can use CSS3 overflow-wrap:break-word property, word-break: break-all, or use overflow-x:hidden of your container element.
More information here, here and here.

Add this to your CSS:
.allcheckbox label
{
word-wrap: break-word;
}
This is forcing overflowing strings to break. Here is the demo: http://jsfiddle.net/62QY8/132/

you can use css for this div
word-wrap:break-word;
overflow:hidden;

Related

why do these similiar functions not work?

I have some divs and if i hover them I want an popup to show. I have six divs and six popups to show but not all at once instead only one per one.
The first function works fine but then the other do not work how can I move them all to one snippet?
<script>
document.addEventListener('DOMContentLoaded', function() {
let elements = document.querySelectorAll('#Mitarbeiter1Punkt');
let popupposts = ['647'];
elements.forEach(function(e, i) {
e.addEventListener('mouseenter', function() {
elementorProFrontend.modules.popup.showPopup({
id: popupposts[i]
});
});
e.addEventListener('mouseleave', function(event) {
jQuery('body').click();
});
});
});
document.addEventListener('DOMContentLoaded', function() {
let elements = document.querySelectorAll('#Mitarbeiter2Punkt');
let popupposts = ['656'];
elements.forEach(function(e, i) {
e.addEventListener('mouseenter', function() {
elementorProFrontend.modules.popup.showPopup({
id: popupposts[i]
});
});
e.addEventListener('mouseleave', function(event) {
jQuery('body').click();
});
});
});
</script>
An alternative option would be to make this data-driven rather code-driven - ie the data is in the HTML, not the js. And as you're using jquery already, make use of jquery.
It's unlikely this will fix the root-cause of your issue as that's not been established (still waiting for complete sample) - this is to show how to combine this into a single function that doesn't need to be changed as you add new HTML.
$(".punkt").on("mouseenter", function() {
var id = $(this).data("popup-id");
$(".popup[data-popup-id='" + id + "']").show();
});
$(".punkt").on("mouseleave", function() {
var id = $(this).data("popup-id");
$(".popup[data-popup-id='" + id + "']").hide();
});
div {
border: 1px solid rebeccapurple;
width: 50px;
height: 50px;
text-align: center;
}
.popup {
display: none;
}
<div class='punkt' data-popup-id='A'>
1
</div>
<div class='punkt' data-popup-id='B'>
2
</div>
<div class='popup' data-popup-id='A'>
A
</div>
<div class='popup' data-popup-id='B'>
B
</div>
I would use an array of objects that maps the div IDs to the popup IDs. Loop over the array and set up all the event listeners.
document.addEventListener('DOMContentLoaded', function() {
let popupMap = [{
div: '#Mitarbeiter1Punkt',
popup: 647
},
{
div: '#Mitarbeiter2Punkt',
popup: 646
}
];
popupMap.forEach(({div, popup}) => {
let e = document.querySelector(div);
e.addEventListener('mouseenter', () => elementorProFrontend.modules.popup.showPopup(popup));
e.addEventListener('mouseleave', () => jQuery('body').click());
});
});
okay so actually i figgered it out myself:
<script>
document.addEventListener('DOMContentLoaded', function() {
let elements = document.querySelectorAll( '.mitarbeiterPunkt' );
let popupposts = [ '647', '656', '660', '664', '664', '668', '672'];
elements.forEach(function(e,i){
e.addEventListener( 'mouseenter', function(){
elementorProFrontend.modules.popup.showPopup( { id: popupposts[i] } );
} );
e.addEventListener( 'mouseleave', function(event){
jQuery('body').click();
});
});
});
</script>

Cannot use onClick in HTML/CSS template in #header

I am using a HTML/CSS template and cannot use the onClick event inside my header. I have tried it everywhere, if I remove the #header class then it works just fine, so it must be something that is preventing it within the js I assume. I have looked in the js and I removed something called hideOnClick, but that did nothing so far.
I will post the JS below. I am rather poor with jquery and things like that so if it is something obvious I apologize.
/*
Prologue by HTML5 UP
html5up.net | #ajlkn
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
*/
(function($) {
skel.breakpoints({
wide: '(min-width: 961px) and (max-width: 1880px)',
normal: '(min-width: 961px) and (max-width: 1620px)',
narrow: '(min-width: 961px) and (max-width: 1320px)',
narrower: '(max-width: 960px)',
mobile: '(max-width: 736px)'
});
$(function() {
var $window = $(window),
$body = $('body');
// Disable animations/transitions until the page has loaded.
$body.addClass('is-loading');
$window.on('load', function() {
$body.removeClass('is-loading');
});
// CSS polyfills (IE<9).
if (skel.vars.IEVersion < 9) $(':last-child').addClass('last-child');
// Fix: Placeholder polyfill.
$('form').placeholder();
// Prioritize "important" elements on mobile.
skel.on('+mobile -mobile', function() {
$.prioritize('.important\\28 mobile\\29', skel.breakpoint('mobile').active);
});
// Scrolly links.
$('.scrolly').scrolly();
// Nav.
var $nav_a = $('#nav a');
// Scrolly-fy links.
$nav_a.scrolly().on('click', function(e) {
var t = $(this),
href = t.attr('href');
if (href[0] != '#') return;
e.preventDefault();
// Clear active and lock scrollzer until scrolling has stopped
$nav_a.removeClass('active').addClass('scrollzer-locked');
// Set this link to active
t.addClass('active');
});
// Initialize scrollzer.
var ids = [];
$nav_a.each(function() {
var href = $(this).attr('href');
if (href[0] != '#') return;
ids.push(href.substring(1));
});
$.scrollzer(ids, { pad: 200, lastHack: true });
// Header (narrower + mobile).
// Toggle.
$('<div id="headerToggle">' + '' + '</div>').appendTo(
$body
);
// Header.
$('#header').panel({
delay: 500,
// hideOnClick: true,
hideOnSwipe: true,
resetScroll: true,
resetForms: true,
side: 'left',
target: $body,
visibleClass: 'header-visible'
});
// Fix: Remove transitions on WP<10 (poor/buggy performance).
if (skel.vars.os == 'wp' && skel.vars.osVersion < 10)
$('#headerToggle, #header, #main').css('transition', 'none');
});
})(jQuery);
example of html that wont work:
<div id="header">
<button
onClick={() => {
console.log('true');
}}
>
Click{' '}
</button>
</div>
$(document).ready(function() {
// This WILL work because we are listening on the 'document',
// for a click on an element with an ID of #test-element
$(document).on("click","#test-element",function() {
alert("click bound to document listening for #test-element");
});
// This will NOT work because there is no '#test-element' ... yet
$("#test-element").on("click",function() {
alert("click bound directly to #test-element");
});
// Create the dynamic element '#test-element'
$('body').append('<div id="test-element">Click mee</div>');
});
This is how to get click functionality with jQuery:
$(function()
{
// Use the .on('click', '#id', function(){}) rather than other options
// for binding click events to dynamically added content as pointed out
// by #Vini
$(document).on("click","#header",function()
{
alert( "Header has been clicked." );
});
$(document).on("click","#buttonToBeClicked",function()
{
alert("Button has been clicked");
});
});
.headerStyle
{
position:relative;
float:left;
width:200px;
height:100px;
background-color:#09f;
text-align:center;
}
.buttonStyle
{
position:relative;
margin: 38px auto;
}
<div id="header" class="headerStyle">
<input type="button" id="buttonToBeClicked" value="clickMe" class="buttonStyle" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Pass "this" from a click event to a function

The following code is not working. I would like to pass "this" (which would be .dot) from the click event to the function, findTargetSlideOfDot but I'm not sure how to go about doing that. thanks
$(document).on('click', '.dot', function() {
var targetSlide = findTargetSlideOfDot;
changeSlide(targetSlide);
})
function findTargetSlideOfDot() {
// find the slide number the user wants to see
var get = $.grep(this.className.split(" "), function(v, i){
return v.indexOf('slide_') === 0;
}).join();
var targetSlide = '.' + get;
return targetSlide;
}
function changeSlide(targetSlide) {
// hide current slide and dot
$('.slide.active, .dot.active').removeClass('active');
$(targetSlide).addClass('active');
}
Here:
$(document).on('click', '.dot', function() {
var targetSlide = $(this);
changeSlide(targetSlide);
})
function changeSlide(targetSlide) {
// hide current slide and dot
//$('.slide.active, .dot.active').removeClass('active');
$(targetSlide).toggleClass('active');
}
.dot{
width: 100px; border: 1px solid black;
padding: 10px; margin: 5px;
}
.dot.active{
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dot">test</div>
Give this a shot, modify your click function like this:
$(document).on('click', '.dot', function(e) {
// e.target should refer to the element with the dot class
})
Here's a functional code pen too: http://codepen.io/csavage1994/pen/Mppxaa
You may want to pass it as a parameter an actually call that function. And the improvement shown by Colton should be applied as well:
$(document).on('click', '.dot', function(e) {
var targetSlide = findTargetSlideOfDot( e.target );
changeSlide(targetSlide);
})
function findTargetSlideOfDot( element ) {
// find the slide number the user wants to see
var get = $.grep(element.className.split(" "), function(v, i){
return v.indexOf('slide_') === 0;
}).join();
var targetSlide = '.' + get;
return targetSlide;
}
function changeSlide(targetSlide) {
// hide current slide and dot
$('.slide.active, .dot.active').removeClass('active');
$(targetSlide).addClass('active');
}
You can choose between:
$(document).on('click', '.dot', function(e) {
findTargetSlideOfDot(e.target);
});
which gives you the element that triggered the event (was clicked)
and:
$(document).on('click', '.dot', function(e) {
findTargetSlideOfDot(e.currentTarget);
});
which gives you the element that had the event listener registered.

keyup event resets input field

Every time I press a key on my keyboard, it sets $(this).val(""); to null and the score variable will be -2.
initialize: function() {
var score = 0;
var wrapper = $('<div>')
.css({
position:'fixed',
top:'0',
left:'0',
width:'100%',
height:'100%'
});
this.wrapper = wrapper;
var self = this;
var text_input = $('<input>')
.addClass('form-control')
.css({
'border-radius':'4px',
position:'absolute',
bottom:'0',
'min-width':'80%',
width:'80%',
'margin-bottom':'10px',
'z-index':'1000'
}).keyup(function() {
var words = self.model.get('words');
for(var i = 0;i < words.length;i++) {
var word = words.at(i);
var typed_string = $(this).val();
var string = word.get('string');
if(string.toLowerCase().indexOf(typed_string.toLowerCase()) === 0) {
word.set({highlight:typed_string.length});
if(typed_string.length === string.length) {
$(this).val("");
score+=10;
$("#dialog").dialog('option', 'title', 'Score : '+score);
}
}
else {
word.set({highlight:0});
$(this).val(""); // problem
score-=2; // problem
$("#dialog").dialog('option', 'title', 'Score : '+score); // problem
}
}
});
$(this.el)
.append(wrapper
.append($('<form>')
.attr({
role:'form'
})
.submit(function() {
return false;
})
.append(text_input)));
text_input.css({left:((wrapper.width() - text_input.width()) / 2) + 'px'});
text_input.focus();
this.listenTo(this.model, 'change', this.render);
},
When I remove the code that causes the problem, it works perfectly every time. inputting the right word and giving the var score score of +10.
How the keyup event works?
The keyup event is triggered every time a key is released.
This means that if the target word is haromy, when typing the h, the event is triggered and the code in the callback is run.
It means that the following will always be false if typing the first letter wrong.
"haromy".toLowerCase().indexOf("f".toLowerCase()) === 0
So the user types a letter, it's not the same first letter, so the field is emptied immediatly by $(this).val("").
Maybe use another event?
If you want to check once the user unfocus the input, the blur event would work.
If you want to make the check when the user clicks a button, use a click event on a new button.
How to stylize a JavaScript application?
Do not set the initial CSS using jQuery's css function. Keep the styling in a CSS file linked in the HTML.
Using the css function only clutters your application logic, makes it difficult to maintain and delay the application of the style to after the JavaScript execution.
How to bind jQuery events with Backbone?
I removed the backbone.js tag from the question as it's irrelevant, but seeing that you're using it and that it could be improved a lot, I'll throw additional information here.
When using Backbone, don't bind events using jQuery directly. Use the Backbone view's events hash.
Your view could look like this:
var View = Backbone.View.extend({
template: '<div class="wrapper"><input class="form-control" /></div>'
events: {
"blur input": "onInputBlur"
},
onInputBlur: function() {
var words = this.model.get('words').each(function(word) {
var typed_string = this.$input.val(),
string = word.get('string');
// Check each word and score here
}, this);
},
initialize: function() {
this.score = 0;
this.listenTo(this.model, 'change', this.render);
},
render: function() {
this.$el.html(this.template);
this.$wrapper = this.$('.wrapper');
this.$input = this.$('input').focus();
return this;
},
});
With styles out, the CSS file would be:
.wrapper {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.input {
border-radius: 4px;
position: absolute;
bottom: 0;
min-width: 80%;
width: 80%;
margin-bottom: 10px;
z-index: 1000;
}

Masonry images overlapping issue

the title pretty much says everything, I did look into the images plugin from masonry yet I had no luck, I wonder if anyone could help?
The script does many things, it has the filter bit, the animation, show/hide, ajax to get the content etc etc. I'd be happy if anyone could investigate into why it is overlapping and how i could solve it based on the code below:
jQuery(function(){
jQuery('#container').masonry({
itemSelector: '.box',
animate: true
});
});
(function ($) {
// Get all menu items with IDs starting with "filter-" and loop over them
$(".menu li[id|=filter]").each(function () {
// Get the ID add extract the page class name from it (remove "filter-" from it)
var type = $(this).attr("id").replace("filter-", "");
// Get the items in the "webbies" list with that class name
var items = $("#container div[class~=" + type + "]");
// Don't do anything if there aren't any
if (items.length == 0) return;
// Get a list of the other items in the list
var others = $("#container>div:not([class~=" + type + "])");
// Add a click event to the menu item
$("a", this).click(function (e) {
// Stop the link
e.preventDefault();
// Close open item
if (openItem) {
close(openItem);
}
items.removeClass("inactive").animate({opacity: 1});
others.addClass("inactive").animate({opacity: 0.2});
});
});
$(".reset-filter a").click(function (e) {
e.preventDefault();
if (openItem) close(openItem);
$("div.box.inactive").removeClass("inactive").animate({opacity: 1});
});
var openItem;
// Opens an item
var open = function (item) {
// Close open item
if (openItem) close(openItem);
item.addClass("loading");
$("img", item).first().hide();
item.width(340);
item.height(600);
if (!item.data('loaded')) {
$("div.fader", item).load($("a", item).first().attr("href") + " #content", function () {
stButtons.locateElements();
stButtons.makeButtons();
stWidget.init();
$("#container").masonry('reloadItems', function () {
$("div.fader", item).animate({opacity: 1}, function () {
item.removeClass("loading");
$('Close"').appendTo(this).click(function (e) {
e.preventDefault();
close(item);
$(document).scrollTo( $("#navigation-block"), 600, {offset:-50} );
});
$("div.info", item).fadeIn("slow", function () {
$(document).scrollTo( $(".info"), 600, {offset:80} );
});
});
});
item.data('loaded', true);
});
} else {
item.removeClass("loading");
$("#container").masonry('reloadItems', function () {
$("div.fader", item).animate({opacity: 1}, function () {
$("div.info", item).fadeIn("slow", function () {
$(document).scrollTo( $(".info"), 600, {offset:80} );
});
});
});
}
// Set open item
openItem = item;
};
// Closes an item
var close = function (item) {
$("div.fader", item).animate({opacity: 0});
$("div.info", item).hide();
item.animate({width: 150, height: 100}, function () {
$("img", item).first().fadeIn("slow");
$("#container").masonry('reloadItems');
});
// Reset open item
openItem = null;
};
$("#container div.box").each(function () {
var item = $(this);
item.data('loaded', false);
$("div.fader", item).css("opacity", 0);
$("a.close", item).click(function (e) {
e.preventDefault();
close(item);
$(document).scrollTo( $("#navigation-block"), 600, {offset:-50} );
});
$("a.showMe", item).click(function (e) {
e.preventDefault();
if (item.hasClass("inactive")) return;
open(item);
});
});
})(jQuery);
</script>
I've experienced the same problem and I developed 2 methods to combat it. First off reload the container after you have appended the onclick-image.
1. container.masonry('reload');
Second, and probably more important, dynamically correct the height of the surrounding div to match the height of the image:
2. // bricks correct height
var brick = $("#marker #container .brick");
brick.each(function() {
var content = $(this).find(">div");
var img = $(this).find("img");
content.css({
height: img.attr("height")
});
});
So my brick is looking like this:
<div style="height: 284px; position: static; top: -133px;" class="test">
<a class="arrow" href="#" target="_self"><img class="img" src="test.jpg" width="374" height="284"></a>
</div>
Edit: In your code you have the same problem, there is no height in the style.
<div style="position: absolute; left: 330px; top: 280px;" class="box item 3d">
And it seems to me you have a problem with the width, too. I think you need to use a smaller width for the column. A good value would be the width of the small image and some border.
jQuery(function(){
var $container = $('#container');
$container.imagesLoaded( function () {
itemSelector: '.box',
animate: true
});
});
Source: jQuery Masonry Images

Categories