Target paragraphs containing only images - javascript

I have a div (blog post) containing multiple paragraphs.
Some of these contain text, other text + images and other only images.
I would like to target only the paragraphs containing only images and set text-align:center
Is this possible using only css or is js required?
Any suggestions?
Thanks

The following adds a special CSS class to all p tags that only contain img tags and whitespace:
$('.blog-post p').each(function(i){ // For each paragraph
if ( ($(this).find('img').length) && // If there's an image
(!$.trim($(this).text()).length)) // and there's no text
{
$(this).addClass('imgOnly'); // Add a special CSS class
}
});
The trim() function is used with text() to determine if the text only contains whitespace.
Sample content:
<div class="blog-post">
<p>Text</p>
<p><span>Text</span></p>
<p><img/></p> <!-- CSS class will be added -->
<p>Text <img/></p>
<p><span>Text</span><img/></p>
<p><img/> Text <img/></p>
<p><img/><img/></p> <!-- CSS class will be added -->
<p><img/> <img/></p> <!-- CSS class will be added -->
</div>

This example will help you: demo on jsFiddle
jQuery code:
$(function() {
var divs = $('.blog-post > div');
$.each(divs, function(i, div) {
/* cache variable */
var $div = $(div);
if ( !($div.find('p')[0]) ) { /* if there are no one p tag inside div */
$div.addClass('only-images');
}
});
});
CSS:
.blog-post > .only-images {
background-color: red; /* color is demo only */
}
So my example will add class only to third div containing only images in this example HTML markup:
<div class="blog-post">
<div>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<p>some text</p>
</div>
<div>
<p>some text</p>
<img src="//placekitten.com/g/100/100" alt="" />
</div>
<div> <!-- only this div would be applied class `only-images` customizable by css -->
<img src="//placekitten.com/g/100/100" alt="" />
<img src="//placekitten.com/g/100/100" alt="" />
</div>
</div>​

To do this you can use javascript and write a function for it, you'll be best of using the javascript library Jquery. When you have a function for it you can later add new paragraphs and images without the need to write more code.
I would have written an example but I don't have much time. I hope I helped you a little

Css is not enough. You may use Css rules based on parents, but not based on children. For example you may target all images that appear inside paragraphs. The properties will apply to the images, and not to the paragraph. Example:
p img
{
/* properties */
}
Options remain Javascript or server-side, for example you could assign a specific class name to the paragraph based on the content (.imageOnly or .mixedContent).

I had to do this without jQuery and I came up with the following:
document.querySelectorAll('p').forEach(function(p) {
// if there's no image, stop
if (p.querySelector('img') === null) {
return;
}
// if there's text, stop
if (p.innerText.trim() !== "") {
return;
}
// otherwise, mark the paragraph
p.classList.add('img-only');
});
Only tested on modern browsers.

Related

Hide First Word of Span by using Css or Jquery

I want to hide first word(ILS) from the span by using css..I have a div which have no class and inside that div there is a span...I just want to hide this word(ILS) from the span...Please guide me where i am wrong
Text displayed like this on the site:
Here is my div:
<div class="purhstdtls-delvry-timesec">
<h5>Test Sample</h5>
<div class="purchase-price"></div>
<div>Some Text Here</div>
<div>
<span>ILS 0.10 / מכירה</span>
</div>
</div>
Css :
.purhstdtls-delvry-timesec>div:nth-child(4)>span:first-word{
display:none;
}
Preferably you add an id to the span or already send the right thing in the backend but:
You can just replace the content.
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script>$(document).ready(
function(){
$('span').text($('span').text().replace('ILS',''));
});
</script>
</head>
<div class="purhstdtls-delvry-timesec">
<h5>Test Sample</h5>
<div class="purchase-price"></div>
<div>Some Text Here</div>
<div>
<span>ILS 0.10 / מכירה</span>
</div>
</div>
It's a dirty solution but it'll work.
You can add wrapper around your required text to be hidden in your case ILS, Try following Code
$(document).ready(function(){
$("span:contains(ILS)").each(function(k,v){
var d = $(v).html();
d = d.replace("ILS", "<div style='display:none'>ILS</div>");
$(v).html(d);
});
});

Make div clickable, only when anchor is present in div (multiple divs)

Given a basic structure how can I turn a series of divs into links without turning every div into a link? Here's an example:
<div class="boxes">
<div class="box"><p>Some text with a link</p></div>
<div class="box"><p>Some text without a link</p></div>
<div class="box"><p>Some text with a link</p></div>
<div class="box"><p>Some text without a link</p></div>
</div>
And the associated jQuery I'm using to make the divs clickable:
$(document).ready(function() {
if($('.boxes p a').length){
$(".boxes .box").click(function() {
window.open($(this).find("a").attr("href"));
return false;
});
}
});
The problem I'm running into is the click function gets applied to all divs instead of only those with links.
The desired behavior is to only create a fully clickable div only when an anchor element is found.
For the purposes of this use case, the div (.box) is generated dynamically and wrapping the element in an anchor tag (<div> </div>) is not possible.
Fiddle: https://jsfiddle.net/fu8xLg0d/
Because you add event listeners on all the .boxes .box classes, which are all your divs.
Just add something like :
$(".boxes .box").has('a')...
to narrow it to those only containing an a element
JSFiddle
use .parent to solve your purpose:
$(document).ready(function() {
if($('.boxes p a').length){
$("a").parent().parent().click(function() {
window.open($(this).find("a").attr("href"));
return false;
});
}
});
But yes, it can even create a problem so i will say to give a class to your link and then call its parent... :)
Plotisateur just beat me by a minute or two! :P
if($('.boxes p a').length){
$(".boxes .box").has('a').click(function() {
window.open($(this).find("a").attr("href"));
return false;
});
Here's the code anyway: https://jsfiddle.net/fu8xLg0d/1/
You can try this.
$(document).ready(function() {
var anchorbox =$(".boxes p a");
if(anchorbox.length>0){
$(anchorbox).parent().click(function() {
window.open($(this).find("a").attr("href"));
return false;
});
}
});
div (.box) is generated dynamically.
Delegate the click event from the body to the target div and on click on the element check if it has anchor tag. For adding the pointer icon create a separate function which will add the icon to the div only if it has an anchor tag as child
$(document).ready(function() {
// separate function to add pointer only if a is present
addClassToElem();
$("body").on('click', '.box', function() {
if ($(this).find('a').length) {
window.open($(this).find("a").attr("href"));
return false;
}
})
});
function addClassToElem() {
$('.box a').each(function(a, b) {
$(this).parent().addClass('linkIcon')
})
}
.linkIcon {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="boxes">
<div class="box">
<p>Some text with a link</p>
</div>
<div class="box">
<p>Some text without a link</p>
</div>
<div class="box">
<p>Some text with a link</p>
</div>
<div class="box">
<p>Some text without a link</p>
</div>
</div>
This little change, helps you to resolve the issue.
$(document).ready(function() {
if($('.boxes p a').length){
$(".boxes .box").click(function() {
if ($(this).children('p').children('a').length) {
window.open($(this).find("a").attr("href"));
return false;
}
});
}
});
the difference from your code is, additionally add a checking
if ($(this).children('p').children('a').length) {
window.open($(this).find("a").attr("href"));
return false;
}

I want to change text with a button

I want to provide all my posts on my blog in 2 languages. I found a way to change the text into another language with buttons. But I can't put any images or other css styles in the text that changes. Then the buttons don't work anymore.
<button onclick="document.getElementById('chgtext').innerHTML='This is the default text. I can't put any css or html in here';">English</button>   <button onclick="document.getElementById('chgtext').innerHTML='Text changed into Another language';">Other language</button>
<div id="chgtext">This is the default text. I can't put any css or html in here</div>
Is there a way I can make something like this but with a code where I'm able to put images, font styles,... in the code?.
Or is there maybe a way to only change the text. And leave the images with multiple divs?
TEXT (changes)
IMAGE
TEXT (changes)
http://oihanevalbuenaredondo.be/2017/01/17/current-favorites-voorbeeld/ --> this is an example of a post i want in 2 languages. I need multiple images, al the text in the post needs to be changed from one language to another, with buttons
You need to iterate over all the children of your element. Using JQuery, and assuming just one level of descendants, you could use something like this...
$('#chgtxt').children().each( function() {
var oldtext = $(this).text();
if (oldtext) {
var newtext = oldtext+" CHANGED. ";
$(this).text(newtext);
}
});
You can create your own using this simple code, it simply gets an entry and replace it by it's value in the array. Ex :
var lang = {
"helloWorld": {
en: "Hello World",
fr: "Bonjour monde"
},
"mynameis": {
en: "My name is",
fr: "Mon nom est"
}
}
$(document).ready(function(){
$(body).find('.trn').each(function($elem){
var currentLang = 'en';
$($elem).html(lang[$($elem).data('trn')][currentLang]);
});
});
For each text your need to add a data with the key and a class trn, just like this.
<span class="trn" data-trn="mynameis"></span> Nicolas
Check this link for more informations
hopes it helps !
Nic
You have a single quote in the text of the first onclick "can't" which is causing the javascript to think that it is the end of the string.
You need to add a backslash "can\'t"
<button onclick="document.getElementById('chgtext').innerHTML='<p>Blue</p>This is the default text. I can\'t put any css or html in here';">English</button>  <button onclick="document.getElementById('chgtext').innerHTML='<p>Blue</p>Text changed into Another language';">Other language</button>
<div id="chgtext"><p>Blue</p>This is the default text. I can't put any css or html in here</div>
<style>
p {color:blue;}
</style>
You need to escape all quotes inside of inserted content. Have a look at snippet and try to click on buttons
<button onclick="document.getElementById('chgtext').innerHTML='This is the default text. <img src=\'http://lorempixel.com/output/nightlife-q-c-50-50-6.jpg\'> NOW I can put any css or <span style=\'color :red;\'>html</span> in here';">English</button>  
<button onclick="document.getElementById('chgtext').innerHTML='Text changed into Another <span style=\'color :red;\'>language</span>';">Other language</button>
<div id="chgtext">This is the default text. I can't put any css or html in here</div>
<p>
<style>
#eng_lang {
display: block;
}
#nl_lang {
display: none;
}
</style>
<button onclick=" document.getElementById('eng_lang').style.display='block'; document.getElementById('nl_lang').style.display='none'">English</button>   <button onclick="document.getElementById('eng_lang').style.display='none';document.getElementById('nl_lang').style.display='block'">Nederlands</button></p>
<div id="eng_lang">
<h2>Here is some text
<span style="color: green;">english</span>
</h2>
<img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRo2yKPonCY-BZrk9s69oH_-gal_yxDRgHxdyXhqP79D0YESVuB" width="120px" height="120px">
Now you can place here any text, tags and images.
</div>
<div id="nl_lang">
<h2>Here is another text
<span style="color: blue;">Netherlands</span>
</h2>
<img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQcE1c0chXugmq_V5qwp51ffAuP7ecGMsWmshnntwAXVGUgVptH" width="100px" height="100px">
Put here whatever you want.
<p>This is paragraph</p>
</div>

Div Inner Content width

I have a div structure as follows:
<div id="showHide">
<div>Alarm</div>
<div>Alarmasdf</div>
<div>Alarmasdffasdff</div>
Is there any way that I can get the width of the content like (Alarmasdffasdff). This content is the largest.
I am able to get the length of the content, but not the width.
Please suggest.
Assuming the div elements have been changed to display: inline, the width of the element will match the content.
If this is not the case I would suggest wrapping the content in a span, or any other suitable inline element, and getting the width of that. For example:
<div id="showHide">
<div>
<span>Alarm</span>
</div>
<div>
<span>Alarmasdf</span>
</div>
<div>
<span>Alarmasdffasdff</span>
</div>
</div>
$('#showhide').find('div:last span').width();
The Width of all of your 'div's is 100% regardless of their content. This is how block level elements behave...
use :contains()
$( "#showhide div:contains('Alarmasdffasdff')").width();
As said by others, width of a block level element is 100% regardless of its content's width. So first you need to change the display of the div to inline-block
<style>
#showHide div
{
display:inline-block;
}
</style>
<div id="showHide">
<div>Alarm
</div>
<div>Alarmasdf
</div>
<div>Alarmasdffasdff
</div>
</div>
$('#showhide>div:contains("Alarmasdffasdff")').innerWidth();
Jquery makes it very easy.
$('#showHide').find('div:last').css('width');
css() returns the computed style of the element, which is the inline styling as well as default styling and any other css selector.
Without jquery it goes a little less "clean"
var mystyle = window.getComputedStyle ? window.getComputedStyle(myobject, null) : myobject.currentStyle;
mystyle.width shows the calculated width, where myobject is the element you want to check.
html :
<div id="showHide">
<div>Alarm</div>
<div>Alarmasdf</div>
<div>Alarmasdffasdff</div>
</div>
script :
var lastDiv = $('#showHide').find('div').last();
var lastDivWidth = lastDiv.width();
alert(lastDivWidth);
jsFiddle
<div id="showHide">
<div class="content" style="width:50px" >Alarm</div>
<div class="content" style="width:60px">Alarmasdf</div>
<div class="content" style="width:120px">Alarmasdffasdff</div>
</div>
Custom width is given so that u can understand the difference, else every div will be having same width, and class content is added for convinience of processing
findWidth("Alarmasdf"); // Calls the function below
function findWidth(value)
{
var width=0;
$(".content").each(function(e){
if($(this).text()==value)
{
width = $(this).width();
}
});
alert(width);
}
Check the fiddle here
http://jsfiddle.net/46LH9/

How to use JavaScript to change div backgroundColor

The HTML below:
<div id="category">
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
</div>
When mouseover the content of div then it's backgroundColor and the h2 (inside this div) backgroundColor change (just like the CSS: hover)
I know this can use CSS (: hover) to do this in modern browser but IE6 doesn't work.
How to use JavaScript (not jQuery or other JS framework) to do this?
Edit:how to change the h2 backgroundColor too
var div = document.getElementById( 'div_id' );
div.onmouseover = function() {
this.style.backgroundColor = 'green';
var h2s = this.getElementsByTagName( 'h2' );
h2s[0].style.backgroundColor = 'blue';
};
div.onmouseout = function() {
this.style.backgroundColor = 'transparent';
var h2s = this.getElementsByTagName( 'h2' );
h2s[0].style.backgroundColor = 'transparent';
};
Adding/changing style of the elements in code is a bad practice. Today you want to change the background color and tomorrow you would like to change background image and after tomorrow you decided that it would be also nice to change the border.
Editing the code every-time only because the design requirements changes is a pain. Also, if your project will grow, changing js files will be even more pain. More code, more pain.
Try to eliminate use of hard coded styles, this will save you time and, if you do it right, you could ask to do the "change-color" task to someone else.
So, instead of changing direct properties of style, you can add/remove CSS classes on nodes. In your specific case, you only need to do this for parent node - "div" and then, style the subnodes through CSS. So no need to apply specific style property to DIV and to H2.
One more recommendation point. Try not to connect nodes hardcoded, but use some semantic to do that. For example: "To add events to all nodes which have class 'content'.
In conclusion, here is the code which I would use for such tasks:
//for adding a css class
function onOver(node){
node.className = node.className + ' Hover';
}
//for removing a css class
function onOut(node){
node.className = node.className.replace('Hover','');
}
function connect(node,event,fnc){
if(node.addEventListener){
node.addEventListener(event.substring(2,event.length),function(){
fnc(node);
},false);
}else if(node.attachEvent){
node.attachEvent(event,function(){
fnc(node);
});
}
}
// run this one when window is loaded
var divs = document.getElementsByTagName("div");
for(var i=0,div;div =divs[i];i++){
if(div.className.match('content')){
connect(div,'onmouseover',onOver);
connect(div,'onmouseout',onOut);
}
}
And you CSS whould be like this:
.content {
background-color: blue;
}
.content.Hover{
background-color: red;
}
.content.Hover h2{
background-color : yellow;
}
Access the element you want to change via the DOM, for example with document.getElementById() or via this in your event handler, and change the style in that element:
document.getElementById("MyHeader").style.backgroundColor='red';
EDIT
You can use getElementsByTagName too, (untested) example:
function colorElementAndH2(elem, colorElem, colorH2) {
// change element background color
elem.style.backgroundColor = colorElem;
// color first contained h2
var h2s = elem.getElementsByTagName("h2");
if (h2s.length > 0)
{
hs2[0].style.backgroundColor = colorH2;
}
}
// add event handlers when complete document has been loaded
window.onload = function() {
// add to _all_ divs (not sure if this is what you want though)
var elems = document.getElementsByTagName("div");
for(i = 0; i < elems.length; ++i)
{
elems[i].onmouseover = function() { colorElementAndH2(this, 'red', 'blue'); }
elems[i].onmouseout = function() { colorElementAndH2(this, 'transparent', 'transparent'); }
}
}
<script type="text/javascript">
function enter(elem){
elem.style.backgroundColor = '#FF0000';
}
function leave(elem){
elem.style.backgroundColor = '#FFFFFF';
}
</script>
<div onmouseover="enter(this)" onmouseout="leave(this)">
Some Text
</div>
It's very simple just use a function on javaScript and call it onclick
<script type="text/javascript">
function change()
{
document.getElementById("catestory").style.backgroundColor="#666666";
}
</script>
Change Bacckground Color
This one might be a bit weird because I am really not a serious programmer and I am discovering things in programming the way penicillin was invented - sheer accident. So how to change an element on mouseover? Use the :hover attribute just like with a elements.
Example:
div.classname:hover
{
background-color: black;
}
This changes any div with the class classname to have a black background on mousover. You can basically change any attribute. Tested in IE and Firefox
Happy programming!
If you are willing to insert non-semantic nodes into your document, you can do this in a CSS-only IE-compatible manner by wrapping your divs in fake A tags.
<style type="text/css">
.content {
background: #ccc;
}
.fakeLink { /* This is to make the link not look like one */
cursor: default;
text-decoration: none;
color: #000;
}
a.fakeLink:hover .content {
background: #000;
color: #fff;
}
</style>
<div id="catestory">
<a href="#" onclick="return false();" class="fakeLink">
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
</a>
<a href="#" onclick="return false();" class="fakeLink">
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
</a>
<a href="#" onclick="return false();" class="fakeLink">
<div class="content">
<h2>some title here</h2>
<p>some content here</p>
</div>
</a>
</div>
To do this without jQuery or any other library, you'll need to attach onMouseOver and onMouseOut events to each div and change the style in the event handlers.
For example:
var category = document.getElementById("catestory");
for (var child = category.firstChild; child != null; child = child.nextSibling) {
if (child.nodeType == 1 && child.className == "content") {
child.onmouseover = function() {
this.style.backgroundColor = "#FF0000";
}
child.onmouseout = function() {
// Set to transparent to let the original background show through.
this.style.backgroundColor = "transparent";
}
}
}
If your h2 has not set its own background, the div background will show through and color it too.
You can try this script. :)
<html>
<head>
<title>Div BG color</title>
<script type="text/javascript">
function Off(idecko)
{
document.getElementById(idecko).style.background="rgba(0,0,0,0)"; <!--- Default --->
}
function cOn(idecko)
{
document.getElementById(idecko).style.background="rgb(0,60,255)"; <!--- New content color --->
}
function hOn(idecko)
{
document.getElementById(idecko).style.background="rgb(60,255,0)"; <!--- New h2 color --->
}
</script>
</head>
<body>
<div id="catestory">
<div class="content" id="myid1" onmouseover="cOn('myid1'); hOn('h21')" onmouseout="Off('myid1'); Off('h21')">
<h2 id="h21">some title here</h2>
<p>some content here</p>
</div>
<div class="content" id="myid2" onmouseover="cOn('myid2'); hOn('h22')" onmouseout="Off('myid2'); Off('h22')">
<h2 id="h22">some title here</h2>
<p>some content here</p>
</div>
<div class="content" id="myid3" onmouseover="cOn('myid3'); hOn('h23')" onmouseout="Off('myid3'); Off('h23')">
<h2 id="h23">some title here</h2>
<p>some content here</p>
</div>
</div>
</body>
<html>

Categories